blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ecf138b57013235364b62412cb7c952119e8b533 | f53891174b71e3b52497b3ab56b30ca7056ef1b7 | /tests/elle/type_traits.cc | 75d1fa353aac642fe3403974200761b6285ca33b | [
"Apache-2.0"
] | permissive | infinit/elle | 050e0a3825a585add8899cf8dd8e25b0531c67ce | 1a8f3df18500a9854a514cbaf9824784293ca17a | refs/heads/master | 2023-09-04T01:15:06.820585 | 2022-09-17T08:43:45 | 2022-09-17T08:43:45 | 51,672,792 | 533 | 51 | Apache-2.0 | 2023-05-22T21:35:50 | 2016-02-14T00:38:23 | C++ | UTF-8 | C++ | false | false | 1,662 | cc | type_traits.cc | # include <type_traits>
# include <elle/test.hh>
// enable_if_exists
template <typename T>
static constexpr std::enable_if_exists_t<typename T::foo, bool>
test(int)
{
return true;
}
template <typename T>
static constexpr bool
test(...)
{
return false;
}
template <typename T>
static constexpr std::enable_if_exists_t<typename T::foo, bool>
test_t(int)
{
return true;
}
template <typename T>
static constexpr bool
test_t(...)
{
return false;
}
struct Foo
{
using foo = int;
};
struct Bar
{};
static_assert(test<Foo>(0), "enable_if_exists failed");
static_assert(!test<Bar>(0), "enable_if_exists failed");
static_assert(test_t<Foo>(0), "enable_if_exists failed");
static_assert(!test_t<Bar>(0), "enable_if_exists failed");
// remove_cv_reference
static_assert(
std::is_same<std::remove_cv_reference<int const&>::type, int>::value,
"remove_cv_reference failed");
static_assert(
std::is_same<std::remove_cv_reference_t<int const&>, int>::value,
"remove_cv_reference failed");
// identity
static_assert(
std::is_same<std::identity<Foo>::type, Foo>::value,
"identity failed");
static_assert(
std::is_same<std::identity_t<Foo>, Foo>::value,
"identity failed");
namespace
{
void get_signature()
{
// get_signature.
auto my_strlen = [](const char*) { return 42; };
static_assert(
std::is_same<std::get_signature<decltype(my_strlen)>,
auto (const char*) -> int>::value,
"get_signature failed");
BOOST_CHECK_EQUAL(my_strlen("42"), 42);
}
}
ELLE_TEST_SUITE()
{
auto& master = boost::unit_test::framework::master_test_suite();
master.add(BOOST_TEST_CASE(get_signature));
}
|
d49af6794e1e370e27a9c90a29a9b18429e546ff | 786cf17c550d155dc8b879e32cfc5499995863b0 | /mylibs/sortingAlgorithms/comparison-based/merge-sort/mergesort.cpp | 265faad137c8d862e46ab54c7bba2704280d16ba | [] | no_license | hbudzik/bertvm.cs.uic.edu | 3f33c93b59b7dc96c45536751dba50fe94215327 | cfa18dba381d010305d35c70f1689c8d7e175894 | refs/heads/master | 2022-02-26T08:10:16.387046 | 2019-09-11T03:20:46 | 2019-09-11T03:20:46 | 120,971,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,960 | cpp | mergesort.cpp | #include <iostream>
using namespace std;
bool DEBUFF = false; //for debugging
// prints out the array
void arrPrint(int *arr);
//will populate the array
void arrpopulate(int* &arr, int n, int &count);
//merge sort method
void msort_intR(int* &arr, int lo, int hi, int* &scratch);
int main(int argc, char** argv)
{
for (int z = 1; z < argc; z++)
{
//processing input flags
if ( argv[z][0] != '-' ) {
cout << "wrong input .. gry -h for help.. " << endl;
return 0;
}else if ( argv[z][1] == 'h' ) {
cout << "prints out -h info help info " << endl;
break;
}else if ( argv[z][1] == 'd' ) {
cout << "DBUGG MODE: ON " << endl;
DEBUFF = true;
continue;
}else{
cout << "-" << argv[z][1] << " is not recognized parameter " << endl;
return 0;
}
}
//creating dynamic array
int n = 5;
int count = 0;
int *arr = new int[n];
//populating the array
arrpopulate(arr, n, count);
//prints out the array
//cout << "original array count: " << count << endl;
//arrPrint(arr);
//sort the array using mergesort method
cout << "count: " << count << endl;
int* scratch = new int[count];
msort_intR(arr, 0, count -1, scratch); //count -1 if ending digit -999 is included
delete[] scratch;
//prints the list after
arrPrint(arr);
return 0;
}
void arrPrint(int *arr)
{
int i = 1;
do{
cout << arr[i-1] << "\t";
if (i % 10 == 0)
{
cout << endl;
}
}while( arr[i++] != -999 );
cout <<endl;
return;
}
void arrpopulate(int* &arr, int n, int &count)
{
int i=0;
int input;
do
{
// takes user input and plugs it into an array
cin >> input;
arr[i] = input;
i++;
if ( input != -999 ){
count++;
}
//checks if arr is full
if (n == i)
{
// new array with double the size in memory
int *newarr = new int[n * 2]; //doubles the size
//deep copy data from old array to new larger array
for (int k = 0; k < n; k++)
{
newarr[k] = arr[k];
}
delete[] arr;
n = 2*n;
arr = newarr;
}
} while (input != -999);
cout << endl;
return;
}
void msort_intR(int* &arr, int lo, int hi, int* &scratch)
{
//base case if list only contains 0 or 1 element than its sorted
if ( lo >= hi ){
return;
}
// "N" = hi-lo +1
//spliting the array in half
int middle = (hi + lo) / 2;
//recursion
msort_intR(arr, lo, middle, scratch);
msort_intR(arr, middle+1, hi, scratch);
int i = lo; // lhs index
int j = middle + 1; // rhs index
int k = 0; // index into scratch[] array that will temporarly store sorted array
while( i <= middle && j <= hi ) {
if (arr[i] <= arr[j]) {
scratch[k] = arr[i];
i++;
}
else{
scratch[k] = arr[j];
j++;
}
k++;
}
//copy leftovers
while ( i <= middle ) {
scratch[k] = arr[i];
i++;
k++;
}
while (j <= hi) {
scratch[k] = arr[j];
j++;
k++;
}
//copy back to an original array
for (k = 0, i=lo; i<=hi; i++, k++)
{
arr[i] = scratch[k];
}
return;
}
|
5345a0357175e2f80f22d9cd385f641fc472e8d3 | d31ba09f33dc70bb820973071f6a7f93a154eddb | /src/next_prime.cpp | afb1e135b89af0eadf082c07160770586d867234 | [
"MIT"
] | permissive | Ironholds/primes | b674283cdfd2f79e580fede662d0a54143d26ab0 | 5cdb24ea3c6ca53770545350631ba55e219581a8 | refs/heads/master | 2023-09-03T03:23:38.541724 | 2023-08-15T13:23:27 | 2023-08-15T13:23:27 | 36,545,345 | 8 | 2 | NOASSERTION | 2023-08-24T16:40:56 | 2015-05-30T05:50:02 | C++ | UTF-8 | C++ | false | false | 1,086 | cpp | next_prime.cpp | #include <Rcpp.h>
#include "primes.h"
//' Find the Next and Previous Prime Numbers
//'
//' Find the next prime numbers or previous prime numbers over a vector.
//'
//' For `prev_prime`, if a value is less than or equal to 2, the function will
//' return `NA`.
//'
//' @param x a vector of integers from which to start the search.
//'
//' @examples
//' next_prime(5)
//' ## [1] 7
//'
//' prev_prime(5:7)
//' ## [1] 3 5 5
//' @aliases prev_prime
//' @return An integer vector of prime numbers.
//' @author Paul Egeler, MS
//' @export
// [[Rcpp::export]]
Rcpp::IntegerVector next_prime(const Rcpp::IntegerVector &x) {
Rcpp::IntegerVector out(x.size());
auto it = out.begin();
for (auto n : x) {
while (!is_prime_(++n))
;
*(it++) = n;
}
return out;
}
//' @rdname next_prime
//' @export
// [[Rcpp::export]]
Rcpp::IntegerVector prev_prime(const Rcpp::IntegerVector &x) {
Rcpp::IntegerVector out(x.size());
auto it = out.begin();
for (auto n : x) {
while (!is_prime_(--n) && n >= 2)
;
*(it++) = n >= 2 ? n : NA_INTEGER;
}
return out;
}
|
ea319cede7e5f4ec64ee0ae0e73683d479ea0b3c | 68e2b2397f5efd7713c500ff0e0bd01df66aff7e | /es_Shred_2-42b/src/SP/enemyDefs.h | f77dbfedd08fe08b166e9349246fd55facfde4f7 | [] | no_license | ericeps/shred2 | ab9605a731e3fb9936dd870f8a9d263dc1ed2f13 | ef3ac878d93597451b55b0156a3433376ce2d12d | refs/heads/master | 2021-01-01T20:44:51.577571 | 2017-07-31T20:36:10 | 2017-07-31T20:36:10 | 98,925,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,259 | h | enemyDefs.h | /* Common Enemy classes.
*/
#ifndef ENEMYDEFS
#define ENEMYDEFS
#include <vector>
#include "defs.h"
#include <iostream>
using namespace std;
class es_idleGest;
struct es_orig : public point3f {
float theta;
};
struct es_moving{
es_moving(float ax,float az,int acc){x=ax;z=az;constcount=acc;count=0;}
float x;
float z;
int constcount;
int count;
};
struct es_idle{
es_idle(float ax,float az,float atheta, int acc){x=ax;z=az;Theta=atheta,constcount=acc;count=0;}
float x;
float z;
float Theta;
int constcount;
int count;
};
struct gestBase{ //convenience class to make vectors of es_moving
gestBase(){;}
virtual void Fix(es_idleGest *AGest,float)=0;
virtual ~gestBase(){;}
};
struct PeekOut : public gestBase{
PeekOut(float ax,float az, float at, float asp,float ad1,float ad2){x=ax;z=az;theta=at;speed=asp;delay01=ad1;delay02=ad2;}
virtual void Fix(es_idleGest *AGest,float);
float x,z,theta,speed;
float delay01;
float delay02;
};
struct Spin : public gestBase{
Spin(){;}
virtual void Fix(es_idleGest *AGest,float);
};
struct Stand : public gestBase{
Stand(){;}
virtual void Fix(es_idleGest *AGest,float);
};
struct es_idleGest{
es_idleGest(std::vector<es_idle> anidle,int anext){Idles=anidle;nextGest=anext;FixBase=NULL;}
void fix(float amt);
void setFixBase(gestBase *abase){if(FixBase!=NULL)
delete FixBase;
FixBase=abase;}
std::vector<es_idle> Idles;
int iiIdle;
int nextGest;
private:
gestBase *FixBase;
};
struct es_sight{
es_sight(float aa,float bb, int adist, int AtkDelay=83, std::vector<es_moving> amov = std::vector<es_moving>())
{A=aa; B=bb; dist=adist; attackDelay=0; CattackDelay=AtkDelay; Moves=amov;iimove=0;};
float A;
float B;
int dist;
std::vector< es_moving > Moves;
int iimove;
int CattackDelay;
int attackDelay;
};
struct mvt{ //convenience class to make vectors of es_moving
mvt(){;}
static es_idleGest mPeekOut(float x, float z, float theta, float speed, int delay1,int delay2);
static std::vector<es_moving> BackAndForth(float x, float y, int count);
static es_idleGest mSpin(float atheta, float aspeed);
static es_idleGest mStand();
};
#endif
|
4c410feb95d3074c33b75c082eb541ec9217dc90 | 6b0af39cddaa68b253cf9a7a6dc68e8d9f334d51 | /L1-005 考试座位号.cpp | 4c00cc02fff5aed7cdb314d98f4e1028f4c174d0 | [] | no_license | fukai98/CCCC-GPLT | 68edae8131b898cd4460da33623d92ff42d516a4 | 4e8b84ca442a73f1d1c3ea98b1aa50a448a7a08f | refs/heads/master | 2020-07-04T05:27:02.415504 | 2019-08-19T16:00:11 | 2019-08-19T16:00:11 | 202,171,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,897 | cpp | L1-005 考试座位号.cpp | /*
L1-005 考试座位号 (15 分)
每个 PAT
考生在参加考试时都会被分配两个座位号,一个是试机座位,一个是考试座位。正常情况下,考生在入场时先得到试机座位号码,
入座进入试机状态后,系统会显示该考生的考试座位号码,考试时考生需要换到考试座位就座。但有些考生迟到了,试机已经结束,
他们只能拿着领到的试机座位号码求助于你,从后台查出他们的考试座位号码。
输入格式:
输入第一行给出一个正整数 N(≤1000),随后 N 行,每行给出一个考生的信息:准考证号
试机座位号 考试座位号。其中准考证号由 16 位数字组成,座位从 1 到 N
编号。输入保证每个人的准考证号都不同,并且任何时候都不会把两个人分配到同一个座位上。考生信息之后,给出一个正整数
M(≤N),随后一行中给出 M 个待查询的试机座位号码,以空格分隔。
输出格式:
对应每个需要查询的试机座位号码,在一行中输出对应考生的准考证号和考试座位号码,中间用
1 个空格分隔。
输入样例:
4
3310120150912233 2 4
3310120150912119 4 1
3310120150912126 1 3
3310120150912002 3 2
2
3 4
输出样例:
3310120150912002 2
3310120150912119 1
*/
#include <iostream>
#include <vector>
using namespace std;
struct Stu {
string id;
int shiji;
int kaoshi;
};
int main() {
int n;
cin >> n;
vector<Stu> stu(n);
for (int i = 0; i < n; ++i)
cin >> stu[i].id >> stu[i].shiji >> stu[i].kaoshi;
int cnt, num;
cin >> cnt;
for (int i = 0; i < cnt; ++i) {
cin >> num;
for (int j = 0; j < n; ++j) {
if (stu[j].shiji == num) {
cout << stu[j].id << " " << stu[j].kaoshi << endl;
break;
}
}
}
return 0;
}
|
ba5d3c88d072e861f6ad760d922d88d8afd04f5e | b5317b08ddec6620382bdd85b791000752766760 | /modules/vis/processors/proxygeometrygenerator.h | 71da948d4c10f5f7c4db5e98b5bd0f9a04b1e1a6 | [
"Apache-2.0"
] | permissive | hmsgit/campvis | 49379dedfb0143e086183c7b89de6efaa6f0dfed | d97de6a86323866d6a8f81d2a641e3e0443a6b39 | refs/heads/master | 2021-04-26T13:16:05.224811 | 2016-02-10T13:56:18 | 2016-02-10T13:56:18 | 121,310,766 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,582 | h | proxygeometrygenerator.h | // ================================================================================================
//
// This file is part of the CAMPVis Software Framework.
//
// If not explicitly stated otherwise: Copyright (C) 2012-2015, all rights reserved,
// Christian Schulte zu Berge <christian.szb@in.tum.de>
// Chair for Computer Aided Medical Procedures
// Technische Universitaet Muenchen
// Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany
//
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
// ================================================================================================
#ifndef PROXYGEOMETRYGENERATOR_H__
#define PROXYGEOMETRYGENERATOR_H__
#include <string>
#include "core/classification/abstracttransferfunction.h"
#include "core/pipeline/visualizationprocessor.h"
#include "core/properties/datanameproperty.h"
#include "core/properties/genericproperty.h"
#include "core/properties/numericproperty.h"
#include "modules/modulesapi.h"
namespace campvis {
/**
* Genereates entry-/exit point textures for the given image and camera.
*/
class CAMPVIS_MODULES_API ProxyGeometryGenerator : public AbstractProcessor {
public:
/**
* Constructs a new ProxyGeometryGenerator Processor
**/
ProxyGeometryGenerator();
/**
* Destructor
**/
virtual ~ProxyGeometryGenerator();
/// To be used in ProcessorFactory static methods
static const std::string getId() { return "ProxyGeometryGenerator"; };
/// \see AbstractProcessor::getName()
virtual const std::string getName() const { return getId(); };
/// \see AbstractProcessor::getDescription()
virtual const std::string getDescription() const { return "Genereates entry-/exit point textures for the given image and camera."; };
/// \see AbstractProcessor::getAuthor()
virtual const std::string getAuthor() const { return "Christian Schulte zu Berge <christian.szb@in.tum.de>"; };
/// \see AbstractProcessor::getProcessorState()
virtual ProcessorState getProcessorState() const { return AbstractProcessor::TESTING; };
DataNameProperty p_sourceImageID; ///< image ID for input image
DataNameProperty p_geometryID; ///< ID for output geometry
IVec2Property p_clipX; ///< clip coordinates for x axis
IVec2Property p_clipY; ///< clip coordinates for y axis
IVec2Property p_clipZ; ///< clip coordinates for z axis
protected:
/// \see AbstractProcessor::updateResult
virtual void updateResult(DataContainer& dataContainer);
/// \see AbstractProcessor::updateProperties
virtual void updateProperties(DataContainer& dc);
static const std::string loggerCat_;
};
}
#endif // PROXYGEOMETRYGENERATOR_H__
|
945b07c3f39b3926d7451f8df0f7105ddb3796a8 | fc422444eb12f7062235e6e09bda562bbe7c7581 | /MaxSumRectangle.cpp | 526e71c4fffbda161f550a2968f6339fdee7bff3 | [
"MIT"
] | permissive | ravikr126/Data-Structures-and-Algorithms-in-cpp | 4e3110927cebb540e9691d38ec7bf8f64f9c0770 | eb60e62f92a78d28231a7041fa6aa7f6c298ec1c | refs/heads/master | 2023-08-19T10:42:07.412487 | 2021-10-01T19:03:44 | 2021-10-01T19:03:44 | 300,021,568 | 1 | 0 | MIT | 2020-09-30T18:43:29 | 2020-09-30T18:43:28 | null | UTF-8 | C++ | false | false | 1,637 | cpp | MaxSumRectangle.cpp | /*
Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix.
Input
First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm.
Output
Output a single integer, maximum sum rectangle.
Constraints
1<=n,m<=100
Sample Input
4 5
1 2 -1 -4 -20
-8 -3 4 2 1
3 8 10 1 3
-4 -1 1 7 -6
Sample Output
29
*/
#include <bits/stdc++.h>
using namespace std;
int kadane(int arr[],int n){
int all_neg=1;
//Loop to check for all negatives;
int neg_max=INT_MIN;
for(int i=0;i<n;i++){
if(arr[i]>0){
all_neg=0;
break;
}
neg_max=max(neg_max,arr[i]);
}
if(all_neg)
return neg_max;
int maxsum=0;
int sum=0;
for(int i=0;i<n;i++){
sum+=arr[i];
if(sum<0)
sum=0;
maxsum=max(sum,maxsum);
}
return maxsum;
}
int main()
{
int n,m;
cin>>n>>m;
int a[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>a[i][j];
}
}
int ans=INT_MIN;
int v[n]={0};
// The Approach is to have vertical sliding window and within that window try to find max contigos
for(int i=0;i<m;i++){
for(int j=i;j<m;j++){
for(int k=0;k<n;k++)
v[k]+=a[k][j];
int t=kadane(v,n);
ans=max(t,ans);
}
fill_n(v,n,0);
}
cout<<ans<<endl;
return 0;
}
|
dae11c74cd631d55cadb115784ec0e5d54f96405 | a58e4057c052c2f4743236f600d06b5191633ee4 | /cf/problem/dp1105/327A.cpp | 8dcd077121bdbc0843fcf494e9cb68af522163df | [] | no_license | nysanier/cf | d454c6afeaa503b39c78febd42c6c0ac49c8f290 | ced8246c42dcf5d1f63770c466c327d9bc0b8a18 | refs/heads/master | 2020-09-08T01:42:24.193949 | 2020-07-26T09:38:49 | 2020-07-26T09:38:49 | 220,973,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | cpp | 327A.cpp | #include <stdio.h>
#include <algorithm>
#include <vector>
#include <set>
#include <string>
#include <limits>
void Dump(const std::vector<int>& vec) {
for (int i = 0; i < (int)vec.size(); ++i) {
printf("[%d] %d\n", i, vec[i]);
}
}
std::vector<int> vec;
int Sum1(int i, int j) {
int sum = 0;
for (int x = i; x < j; ++x) {
if (vec[x] == 1) {
sum += 1;
}
}
return sum;
}
int main() {
int n;
scanf("%d", &n);
vec.resize(n);
for (int i = 0; i < (int)vec.size(); ++i) {
scanf("%d", &vec[i]);
}
int max_val = 0;
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
int v1 = Sum1(0, i);
int v2 = (j + 1 - i) - Sum1(i, j + 1);
int v3 = Sum1(j + 1, n);
max_val = std::max(max_val, v1 + v2 + v3);
}
}
printf("%d\n", max_val);
return 0;
}
|
310326846654fba029ecbda4547855d3782983da | e319b601cbe5114d83145a0d946828329bcd3562 | /fight_UI.cpp | 866d6dcb8b8e232c753dd950023541223eb6353e | [] | no_license | K-Ysz/file | 2894c8feccbeed48ffe3efccafedc235b423489f | 26d4d28a1eabc5ff8fb822acaaf8c6d87ca721b6 | refs/heads/master | 2020-04-03T02:55:24.076462 | 2018-10-28T13:20:24 | 2018-10-28T13:20:24 | 154,971,595 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,901 | cpp | fight_UI.cpp | #include "DxLib.h"
#define WinX 1280
#define WinY 720 // この二つはウィンドウサイズ
#define GRAY GetColor(105, 105, 105) // 色リスト
#define BLACK GetColor( 0, 0, 0)
#define WHITE GetColor(255, 255, 255)
#define RED GetColor(255, 0, 0)
#define GREEN GetColor( 0, 255, 0)
#define YELLOW GetColor(255, 255, 0)
#define PNT 32
#define HEIGHT 48
#define WIDTH HEIGHT * 10
#define SIZE HEIGHT / 2
// グロ変
int HP_me = 16, HP_you = 4;
// 基本画面構築
void CreateMain(void){
SetFontSize(SIZE);
// メッセージボックス
DrawBox(0, WinY - HEIGHT * 2, WinX + 1, WinY + 1, WHITE, TRUE);
DrawBox(0, WinY - HEIGHT * 2, WinX + 1, WinY + 1, BLACK, FALSE);
DrawFormatString(SIZE / 2, WinY - HEIGHT * 2 + SIZE / 2, BLACK,
"メッセージボックス\n\nサンプルテキスト");
// ステータス描画
// 相手側下地
DrawBox(-1, PNT, PNT * 3 + WIDTH + 1, PNT * 4 + 1, WHITE, TRUE);
DrawBox(-1, PNT, PNT * 3 + WIDTH + 1, PNT * 4 + 1, BLACK, FALSE);
// 相手のHP枠下地
DrawBox(PNT, PNT * 3 / 2, PNT + WIDTH + 1, PNT * 3 / 2 + SIZE + 1, BLACK, TRUE);
// 相手の残りHPのテキスト
DrawFormatString(PNT + WIDTH, PNT * 3 / 2, BLACK, "%2d", HP_you);
// 相手のHPバー
// 現在値によって色変化
DrawBox(PNT, PNT * 3 / 2, PNT + SIZE * HP_you + 1, PNT * 3 / 2 + SIZE + 1,
HP_you > 10 ? GREEN : (HP_you > 4 ? YELLOW : RED), TRUE);
// 相手の名前
DrawFormatString(PNT, PNT * 3 / 2 + SIZE, BLACK, "<ここに敵の名前>");
// ターンの行動
DrawBox(PNT * 3 + WIDTH - SIZE * 5, PNT * 4 - SIZE * 2,
PNT * 3 + WIDTH + 1, PNT * 4 + 1, BLACK, FALSE);
DrawFormatString(PNT * 3 + WIDTH - SIZE * 9 / 2, PNT * 4 - SIZE * 3 / 2, BLACK,
"こうどう");
// 自分側下地
DrawBox(WinX - (PNT * 3 + WIDTH), WinY - (PNT * 4 + HEIGHT * 2),
WinX + 2, WinY - (PNT + HEIGHT * 2) + 1, WHITE, TRUE);
DrawBox(WinX - (PNT * 3 + WIDTH), WinY - (PNT * 4 + HEIGHT * 2),
WinX + 2, WinY - (PNT + HEIGHT * 2) + 1, BLACK, FALSE);
// 自分のHP枠下地
DrawBox(WinX - (PNT + WIDTH), WinY - (PNT * 7 / 2 + HEIGHT * 2),
WinX - PNT + 1, WinY - (PNT * 7 / 2 + HEIGHT * 2) + SIZE + 1, BLACK, TRUE);
// 自分の残りHPのテキスト
DrawFormatString(WinX - (PNT + WIDTH + SIZE + 4),
WinY - (PNT * 7 / 2 + HEIGHT * 2), BLACK, "%2d", HP_me);
// 自分のHPバー
// 現在値によって色変化
DrawBox(WinX - (PNT + WIDTH), WinY - (PNT * 7 / 2 + HEIGHT * 2),
WinX - (PNT + WIDTH) + SIZE * HP_me + 1, WinY - (PNT * 7 / 2 + HEIGHT * 2) + SIZE + 1,
HP_me > 10 ? GREEN : (HP_me > 4 ? YELLOW : RED), TRUE);
// ターンの行動
DrawBox(WinX - (PNT * 3 + WIDTH), WinY - (PNT * 4 + HEIGHT),
WinX - (PNT * 3 + WIDTH) + SIZE * 5 + 1, WinY - (PNT + HEIGHT * 2) + 1, BLACK, FALSE);
DrawFormatString(WinX - (PNT * 3 + WIDTH) + SIZE / 2, WinY - (PNT * 4 + HEIGHT) + SIZE / 2, BLACK,
"こうどう");
}
// 構築画面の設計
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ){
// もろもろ起動前の初期設定
ChangeWindowMode(TRUE);
SetWindowSizeChangeEnableFlag(FALSE, FALSE);
SetGraphMode(1920, 1080, 32);
SetWindowSize(WinX, WinY);
if( DxLib_Init() == -1 ){
return -1;
}
// ウィンドウ生成:画面サイズは仮
DrawBox(0, 0, WinX + 1, WinY + 1, GRAY, TRUE);
// 基本画面構築
CreateMain();
int Mx, My;
do{
if((GetMouseInput() & MOUSE_INPUT_LEFT) != 0){
GetMousePoint(&Mx, &My);
// ※※※デバッグ用、左上クリックすると消えます
if(Mx < PNT && My < PNT) break;
}
}while(1);
DxLib_End();
return 0;
}
|
c0f608e5d37e4699c96344e563da5be47a47759f | d6a3e21aaa26a86c648dc17d0a5d664d8d97e4c4 | /Sdk/Core/Serialization/Json/JsonObject.h | 83a2e18c90823254ec8980e802939a86e9416765 | [] | no_license | Neomer/EnergyExpert | 18faccfb695e7ee431d8a419b4e5d71563bb1253 | 0bb6caeb2b19d67d84c74f38015692d49a584a6d | refs/heads/dev | 2020-04-29T03:29:38.200805 | 2019-04-24T05:35:50 | 2019-04-24T05:35:50 | 175,811,853 | 0 | 0 | null | 2019-04-24T05:34:27 | 2019-03-15T11:58:28 | C++ | UTF-8 | C++ | false | false | 566 | h | JsonObject.h | #ifndef JSONOBJECT_H
#define JSONOBJECT_H
#include <Sdk/export.h>
#include <unordered_map>
#include <deque>
#include <Sdk/Core/Serialization/Json/JsonValue.h>
namespace energy { namespace core { namespace serialization { namespace json {
/**
* @brief Объект Json.
*/
class SDKSHARED_EXPORT JsonObject final : public JsonValue
{
public:
JsonObject();
JsonValue &operator[](const std::string &name);
JsonValue &operator[](const char *name);
private:
std::unordered_map<std::string, JsonValue *> _map;
};
} } } }
#endif // JSONOBJECT_H
|
aecbbe523e7a59b3a9259768e92f03ad57a36761 | 0ff8b50c9c1fe7142959e3b427f753241f8c910f | /数据结构学习与实验指导/4-6搜索树判断.cpp | 55824e26163fda0016decaeb54b3aa2d72724706 | [] | no_license | JiangQinHong/MyCode_Practice | 4e3113218c815c7992ffe5859c73c51625cbca85 | 37f56c59429782f849b1b940ce7df74773ee8ab7 | refs/heads/master | 2021-01-19T07:57:25.290871 | 2014-09-03T14:12:20 | 2014-09-03T14:12:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,497 | cpp | 4-6搜索树判断.cpp | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int PostFix[1001];
int PreFix[1001];
void JudgeAndCompute(int Flag,int Head,int End);
int Count;
int main()
{
int N;
scanf("%d",&N);
Count=N-1;
int Input;
for(int i=0;i<N;i++)
{
scanf("%d",&Input);
PreFix[i]=Input;
}
JudgeAndCompute(3,0,N-1);
printf("YES\n");
printf("%d",PostFix[0]);
for(int i=1;i<N;i++)
{
printf(" %d",PostFix[i]);
}
printf("\n");
system("pause");
return 0;
}
void JudgeAndCompute(int Flag,int Head,int End)
{
int LHead,LEnd,RHead,REnd;
int MFlag;
int ToBe=1;
PostFix[Count]=PreFix[Head];
Count--;
if(Head==End)
{
return;
}
if(PreFix[Head]>PreFix[Head+1])
MFlag=1;
else
MFlag=2;
LHead=Head+1;
LEnd=Head;
RHead=REnd=LHead;
int Tag=0;
for(int i=Head+1;i<=End;i++)
{
if(MFlag==1)
{
if(PreFix[i]<PreFix[Head])
{
LEnd++;
if(Tag==1)
{
ToBe=0;
break;
}
}
else
{
if(Tag==0)
{
RHead=i;
Tag=1;
}
if(Tag==1)
{
REnd=i;
}
}
}
if(MFlag==2)
{
if(PreFix[i]>=PreFix[Head])
{
LEnd++;
if(Tag==1)
{
ToBe=0;
break;
}
}
else
{
if(Tag==0)
{
RHead=i;
Tag=1;
}
if(Tag==1)
{
REnd=i;
}
}
}
}//end of for
if(RHead==LHead)
MFlag=3;
if(!ToBe||(MFlag!=Flag&&Flag!=3&&MFlag!=3))
{
printf("NO\n");
exit(0);
}
if(RHead!=LHead)
JudgeAndCompute(MFlag,RHead,REnd);
JudgeAndCompute(MFlag,LHead,LEnd);
} |
3a8bf763fc412590b744659d51eeceec707336a9 | 806640ac3ff1d8ed289aa99cbdc7231a495b77da | /C++/Fion/random2.cpp | 79b7e980ab30559abe1736e1d67b6128526064f5 | [] | no_license | whycantiputnothing/randomprojects | 9f743cd8551f5a5259505e81a065fd60c478a6c9 | 4ca9543c9b85eeb363fc73b5fbd3d229e275426f | refs/heads/master | 2022-10-15T01:19:22.396572 | 2018-12-06T05:29:02 | 2018-12-06T05:29:02 | 51,283,766 | 0 | 1 | null | 2022-10-09T19:35:01 | 2016-02-08T07:10:13 | Python | UTF-8 | C++ | false | false | 563 | cpp | random2.cpp | #include <iostream>
#include <string>
using namespace std;
string make_message1(string msg);
int number_calculator(int &a, int b);
int main()
{
int x(9), y(5);
string m = "Hello!";
int z = number_calculator(x, y);
string msg = make_message1(m);
return 0;
}
string make_message1(string msg) {
return msg;
}
// Precondition: n > 1.
// n = number of elements in array x
// Postcondition: standard deviation is written to standard output
// with 3 decimal places
int number_calculator(int &a, int b){
return 0;
}
|
05b9e93ee907c35d1049a4df31e5977d4fd275c6 | b7056c4edc0ecb087fb6bc7a199d267e58df3f91 | /AnnihilationCharacter/AnnihilationCharacter/generic/KeyControl.hpp | 5c28b929fa98faa1e56c36f7d5ff208c8426f06f | [] | no_license | elipmoc/AnnihilationCharacter | e9e7276c9eb01b3c89d92a2e25cb861a936d1089 | 6fda4c8bb69f6bb3e89682018fb2f9603d92b6c4 | refs/heads/master | 2020-12-02T19:19:29.642985 | 2017-07-15T05:16:18 | 2017-07-15T05:16:18 | 96,323,975 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 492 | hpp | KeyControl.hpp | #pragma once
#include <memory>
#include <array>
namespace generic {
//キーを管理するクラス
//スレッドセーフではないシングルトン
class KeyControl {
static constexpr size_t keyMax=256;
std::array<size_t, keyMax> countKey;
public:
static KeyControl* GetInstance() {
static KeyControl* instance = new KeyControl;
return instance;
}
//キー判定を更新
void UpdateKey();
//特定キーの情報を得る
size_t GetKey(int keyCode);
};
} |
651d2dbfdac8b03e90b0a1391c07c4064a31dbc6 | 9f29bf7b503bdd25ef89aed7d89a0d1add22b652 | /MQTTPublisher.h | 7e95d1c3085a6537998c5e56598b247d36d67e45 | [
"MIT"
] | permissive | diversit/esp8266-dsmr | f161768831150316a08368626b25884a82b52a8b | 8b742f5738855fdc622db9568193136cbe26d404 | refs/heads/master | 2023-04-29T06:35:25.361330 | 2021-04-16T08:55:12 | 2021-04-16T08:55:12 | 358,227,865 | 0 | 0 | MIT | 2021-04-16T06:55:16 | 2021-04-15T11:04:38 | null | UTF-8 | C++ | false | false | 743 | h | MQTTPublisher.h | #define MQTT_SOCKET_TIMEOUT 5
#pragma once
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <vector>
#include "PubSubClient.h"
#include "WiFiClient.h"
#include "Logger.h"
#define RECONNECT_TIMEOUT 15000
extern bool hasMQTT;
extern bool hasWIFI;
class MQTTPublisher
{
private:
Logger logger;
bool _debugMode;
String _clientId;
bool isStarted;
uint32_t lastConnectionAttempt = 0; // last reconnect
uint32_t lastUpdateMqtt; // last data send
bool reconnect();
String getTopic(String name);
public:
MQTTPublisher(String clientId = String(ESP.getChipId(), HEX));
~MQTTPublisher();
void start();
void stop();
void handle();
bool publishOnMQTT(String topic, String msg);
};
|
a099ed7a6b5d6000ab974bfff841c54aa7a4fc30 | 5647bb71bd8778c2368657cc71132f5a9ddde713 | /ser.cpp | a3b3242e0fdbac50394ca0f3bceea4ba39e114ef | [] | no_license | AnikaTabassum/spl1 | 0fa137bf6c403b747d0cdd4bd6f023adb5f89d22 | 41eb75afcc23a4fbcde46a7d5e6d1767fe2b3c8a | refs/heads/master | 2021-05-11T05:19:47.134675 | 2018-05-30T04:50:21 | 2018-05-30T04:50:21 | 117,958,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,766 | cpp | ser.cpp | #include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<fstream>
#include<netinet/in.h>
using namespace std;
char strings[5000][5000];
ofstream oFile;
int filecounter=1, byteCounter=1;
int totalByte2(const char* input) //counts the total byte of the splittedfiles
{
ifstream iFile;
iFile.open(input,ios::binary);
int byt=0;
if(iFile.is_open())
{
char ch;
while(!iFile.eof())
{
iFile.get(ch);
byt++;
}
//cout<<byt;
}
iFile.close();
return byt;
}
void openforwrite(int filecounter) {
char fileoutputname[15];
sprintf(fileoutputname, "testf%d", filecounter);
sprintf(strings[filecounter-1],fileoutputname);
printf("%s\n",fileoutputname);
oFile.open(fileoutputname,ios::binary);
}
int mergeFiles(int n) //merges the splitted files
{
ofstream oFile2;
oFile2.open("now.jpg",ios::binary);
char buffer[4097];
for (int i = 0; i < n; ++i)
{
const char* fname = strings[i];
printf("merging %s\n",fname);
ifstream iFile2;
iFile2.open(fname,ios::binary);
if(iFile2.is_open())
{
while(!iFile2.eof())
{
if(oFile2.is_open()||(iFile2.eof()))
{
for(int j=0;j<totalByte2(fname);j++)
{
char ch;
iFile2.get(ch);
if(!iFile2.eof())
oFile2<<ch;
}
}
iFile2.close();
}
}
}
oFile2.close();
return 0;
}
void writeInFile(char server_response[], int filecounter, int byteCounter)
{
int x=0;
openforwrite(filecounter);
while(server_response[x]!='\0')
{
if(oFile.is_open())
{
char ch= server_response[x];
oFile<<ch;
byteCounter++;
}
x++;
}
oFile.close();
byteCounter=1;
filecounter++;
openforwrite(filecounter);
}
int merging(int sss, char server_response[]) //merges the splitted files
{
ofstream oFile2;
oFile2.open("now.jpg",ios::app);
char buffer[4097];
for (int i = 0; i < sss; ++i)
{
char ch=server_response[i];
oFile2<<ch;
}
oFile2.close();
return 0;
}
void receiveing()
{
//create a socket
int network_socket;
network_socket = socket(AF_INET, SOCK_STREAM, 0); //socket(int domain, int type, int protocol)
// specify an address for two socket
struct sockaddr_in server_address; //declaring the stucture of theaddress
server_address.sin_family= AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr= INADDR_ANY;
int connection_status= connect(network_socket, (struct sockaddr *)&server_address, sizeof(server_address)); //
if(connection_status==-1)
printf("Error\n");
int socket(int domain, int type, int protocol);
char server_response [416415]; //buffer
recv(network_socket, &server_response, sizeof(server_response),0);
//int sss=sizeCheck(server_response);
writeInFile(server_response,filecounter,byteCounter);
//cout<<sss<<endl;
//merging(sss,server_response);
}
int convertion(char server_response[])
{
/*for(int i=0;server_response[i]!='\0';i++)
{
//cout<<server_response[i];
int h=server_response[i]-'0';
cout<<h<<endl;
}*/
return atoi(server_response);
}
int receiveFileNumbers()
{
int network_socket;
network_socket = socket(AF_INET, SOCK_STREAM, 0); //socket(int domain, int type, int protocol)
// specify an address for two socket
struct sockaddr_in server_address; //declaring the stucture of theaddress
server_address.sin_family= AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr= INADDR_ANY;
int connection_status= connect(network_socket, (struct sockaddr *)&server_address, sizeof(server_address)); //
if(connection_status==-1)
printf("Error\n");
int socket(int domain, int type, int protocol);
char server_response [416415]; //buffer
recv(network_socket, &server_response, sizeof(server_response),0);
/*for(int i=0;server_response[i]!='\0';i++)
cout<<server_response[i];*/
int numberOfFiles=convertion(server_response) ;
//cout<<numberOfFiles<<endl;
return numberOfFiles;
}
int receiveFileSize()
{
int network_socket;
network_socket = socket(AF_INET, SOCK_STREAM, 0); //socket(int domain, int type, int protocol)
// specify an address for two socket
struct sockaddr_in server_address; //declaring the stucture of theaddress
server_address.sin_family= AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr= INADDR_ANY;
int connection_status= connect(network_socket, (struct sockaddr *)&server_address, sizeof(server_address)); //
if(connection_status==-1)
printf("Error\n");
int socket(int domain, int type, int protocol);
char server_response [416415]; //buffer
recv(network_socket, &server_response, sizeof(server_response),0);
for(int i=0;server_response[i]!='\0';i++)
cout<<"x"<<server_response[i];
int fileSize=convertion(server_response) ;
cout<<fileSize<<endl;
return fileSize;
}
int main()
{
int n=receiveFileNumbers();
// for(int i=0;i<n;i++){
int size=receiveFileSize();
cout<<size<<endl;
//}
//receiveing();
//close(network_socket);
return 0;
}
|
9dad054f974f8f98565ba5a4d537a61d7184ba09 | b81c2eb1d170cbe17a52176f544381de47f29fe7 | /include/tpqueue.h | 8866c78ed617374febf1e71c5a0664c1f39e7197 | [] | no_license | BaikinaNastya/ADS-5 | dfd63a879b460af33f915f99a70d9fbf5cec2f85 | c822cd1b49dfd0ab740003b82dc99c0688b36b45 | refs/heads/master | 2022-07-21T10:25:32.738816 | 2020-05-17T14:39:46 | 2020-05-17T14:39:46 | 264,686,878 | 0 | 0 | null | 2020-05-17T14:35:14 | 2020-05-17T14:35:13 | null | UTF-8 | C++ | false | false | 1,969 | h | tpqueue.h | #include <cassert>
template<typename T>
class TPQueue
{
struct ITEM
{
T data;
ITEM * next;
};
public:
TPQueue():head(nullptr),tail(nullptr){}
~TPQueue();
void push(const T&);
T pop();
void print() const;
private:
TPQueue::ITEM* create(const T&);
ITEM *head;
ITEM *tail;
};
template<typename T>
typename TPQueue<T>::ITEM* TPQueue<T>::create(const T& data)
{
ITEM *item=new ITEM;
item->data.ch=data.ch;
item->data.prior=data.prior;
item->next=nullptr;
return item;
}
template<typename T>
TPQueue<T>::~TPQueue()
{
while(head)
pop();
}
template<typename T>
void TPQueue<T>::push(const T& data)
{
if (data.prior>10 || data.prior<1)
return ;
if(tail && head)
{
ITEM *step=head, *prev = head;
while (step->data.prior >= data.prior) {
if (step==tail) {
break;
}
prev=step;
step=step->next;
}
if (step==head && step->data.prior != data.prior) {
step=create(data);
step->next=head;
head=step;
}
else if (tail->data.prior >= data.prior) {
tail->next=create(data);
tail=tail->next;
return ;
}
else {
ITEM *tmp=prev->next;
step=create(data);
prev->next=step;
step->next=tmp;
}
}
else
{
head=create(data);
tail=head;
}
}
template<typename T>
T TPQueue<T>::pop()
{
if(head)
{
ITEM *temp=head->next;
T data=head->data;
delete head;
head=temp;
return data;
}
}
template<typename T>
void TPQueue<T>::print() const
{
ITEM *temp=head;
while(temp)
{
std::cout<< temp->data.ch <<" "<< temp->data.prior <<std::endl;
temp=temp->next;
}
}
struct SYM
{
char ch;
int prior;
};
|
125ecc05d81528ccdd13a193213cbffa20705b00 | 3b8b45149196c81b498725edc7b42e413d012724 | /Interviews/Arrays/Sort/merge_sort.cpp | d716bc09947ac448f6a0a6cd2035de12cca1152e | [] | no_license | Zildj1an/Codes | a3cdbe9ec564314293fb29d24835c24a499337d6 | aa92789004913b5ac20b4479de475960e6c27ddb | refs/heads/main | 2023-03-09T12:22:38.448135 | 2021-01-13T17:37:28 | 2021-01-13T17:37:28 | 341,924,304 | 0 | 0 | null | 2021-02-24T14:20:18 | 2021-02-24T14:20:17 | null | UTF-8 | C++ | false | false | 1,166 | cpp | merge_sort.cpp | #include<bits/stdc++.h>
using namespace std;
void merge(int arr[], int l,int m,int r)
{
int i,j,k;
int n1= m - l+ 1;
int n2 = r - m;
int L[n1],R[n2];
for(i=0;i<n1;i++)
{
L[i]= arr[l+i];
}
for(j=0;j<n2;j++)
{
R[j]= arr[m+1+j];
}
i = 0;
j = 0;
k=l;
while(i < n1 && j < n2)
{
if(L[i]<=R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while(i<n1)
{
arr[k] = L[i];
i++;
k++;
}
while(j<n2)
{
arr[k] = R[j];
i++;
j++;
}
}
void printArray(int arr[],int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
void merge_sort(int arr [], int l,int r)
{
if(l<r)
{
int m = (l+r- 1) /2;
merge_sort(arr,l,m);
merge_sort(arr,m + 1,r);
merge(arr,l,m,r);
}
}
int main()
{
int arr [6] = {12,11,13,5,6,7};
printArray(arr,6);
merge_sort(arr,0,5);
printArray(arr,6);
return 0;
} |
4ec645ca44e1a8c044ea150af64f8608887bfbf0 | eb21b708bab1e178dcdccdb8ab83fbc5be275b4c | /src/headers/imp/stream/string_input_stream.hpp | da0fbf81ccf6b8efb283905a4a08e16c8bd66c1d | [] | no_license | chenhowa/rdbms | 25e1021f01daf4a5582f3687c7f8f72c3fcebc9e | 22f442a135f1470a48b9578f12a0225b4c43a3d8 | refs/heads/master | 2020-03-27T09:11:41.880434 | 2018-09-07T16:48:43 | 2018-09-07T16:48:43 | 146,320,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,089 | hpp | string_input_stream.hpp |
#ifndef STRING_INPUT_STREAM_HPP
#define STRING_INPUT_STREAM_HPP
#include "i_string_input_stream.hpp"
#include <sstream>
#include <string>
#include <memory>
#include <fruit/fruit.h>
class StringInputStream : public IStringInputStream {
private:
std::unique_ptr<std::istringstream> input;
public:
INJECT( StringInputStream() );
virtual char get() override;
virtual char peek() override;
virtual IInputStream& ignore( unsigned n, char delim) override;
virtual IInputStream& read(unsigned in, char* s) override;
virtual bool good() const override;
virtual bool eof() const override;
virtual bool bad() const override;
virtual bool fail() const override;
virtual bool operator! () const override;
virtual explicit operator bool() const override;
virtual void clear(std::iostream::iostate state) override;
virtual ~StringInputStream() { };
virtual void setContent(const std::string &s);
virtual std::string getContent();
};
fruit::Component<IStringInputStream> getIStringInputStream();
#endif // STRING_INPUT_STREAM_HPP |
41617e2d2da1d06b48ea7da361142b240b7f9bf6 | a76fc4b155b155bb59a14a82b5939a30a9f74eca | /AtelierCinema/Admin/DlgModifTempo.cpp | 25f76510c5878a4a167c4773a70d2808596f5046 | [] | no_license | isliulin/JFC-Tools | aade33337153d7cc1b5cfcd33744d89fe2d56b79 | 98b715b78ae5c01472ef595b1faa5531f356e794 | refs/heads/master | 2023-06-01T12:10:51.383944 | 2021-06-17T14:41:07 | 2021-06-17T14:41:07 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 9,223 | cpp | DlgModifTempo.cpp | // DlgModifTempo.cpp : implementation file
//
#include "stdafx.h"
#include "admin.h"
#include "DlgModifTempo.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// L'Application
extern CAdminApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CDlgModifTempo dialog
CDlgModifTempo::CDlgModifTempo(CWnd* pParent /*=NULL*/)
: CDialog(CDlgModifTempo::IDD, pParent)
{
//{{AFX_DATA_INIT(CDlgModifTempo)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CDlgModifTempo::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgModifTempo)
DDX_Control(pDX, IDC_CADRE, m_Cadre1);
DDX_Control(pDX, IDC_PASSAGE92, m_passage92);
DDX_Control(pDX, IDC_PASSAGE91, m_passage91);
DDX_Control(pDX, IDC_PASSAGE82, m_passage82);
DDX_Control(pDX, IDC_PASSAGE81, m_passage81);
DDX_Control(pDX, IDC_PASSAGE72, m_passage72);
DDX_Control(pDX, IDC_PASSAGE71, m_passage71);
DDX_Control(pDX, IDC_PASSAGE62, m_passage62);
DDX_Control(pDX, IDC_PASSAGE61, m_passage61);
DDX_Control(pDX, IDC_PASSAGE52, m_passage52);
DDX_Control(pDX, IDC_PASSAGE51, m_passage51);
DDX_Control(pDX, IDC_PASSAGE42, m_passage42);
DDX_Control(pDX, IDC_PASSAGE41, m_passage41);
DDX_Control(pDX, IDC_PASSAGE32, m_passage32);
DDX_Control(pDX, IDC_PASSAGE31, m_passage31);
DDX_Control(pDX, IDC_PASSAGE22, m_passage22);
DDX_Control(pDX, IDC_PASSAGE21, m_passage21);
DDX_Control(pDX, IDC_PASSAGE12, m_passage12);
DDX_Control(pDX, IDC_PASSAGE11, m_passage11);
DDX_Control(pDX, IDC_PASSAGE102, m_passage102);
DDX_Control(pDX, IDC_PASSAGE101, m_passage101);
DDX_Control(pDX, IDC_TEMPO, m_libtempo);
DDX_Control(pDX, IDC_COMBOPERIODE, m_periode);
DDX_Control(pDX, IDC_LISTTEMPO, m_ListTempo);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgModifTempo, CDialog)
//{{AFX_MSG_MAP(CDlgModifTempo)
ON_BN_CLICKED(IDC_OK, OnOk)
ON_BN_CLICKED(IDC_ANNULER, OnAnnuler)
ON_LBN_SELCHANGE(IDC_LISTTEMPO, OnSelchangeListtempo)
ON_EN_CHANGE(IDC_TEMPO, OnChangeTempo)
ON_CBN_SELCHANGE(IDC_COMBOPERIODE, OnSelchangeComboperiode)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgModifTempo message handlers
void CDlgModifTempo::OnOk()
{
UpdateData(1);
CString libelle;
m_libtempo.GetWindowText(libelle);
// controle de la saisie
if(libelle=="")
{
MessageBox(" Saisie incorrecte\nVeuillez préciser un libellé pour le tempo");
return;
}
// le libellé est il déjà utilisé
if((theApp.base.GetTableTempo()->ExisteLibelleTempo(libelle))&&(m_OldLibelleTempo!=libelle))
{
CString message;
message.Format("Le libellé %s existe : Veuillez choisir un autre libellé",libelle);
MessageBox(message);
return;
}
// y a t il des passages pour le tempo?
if(!IsPassage())
{
MessageBox(" Tempo non défini\nVeuillez sélectionner le motif du tempo");
return;
}
// mise à jour du tempo
{
tagTempo tempo;
// chaine de définition
CString deftempo;
// variables de comptage pour l'équilibrage
int count1=0,count2=0;
// On boucle sur les semaines de la période
for(int sem=0;sem<m_periode.GetCurSel()+1;sem++)
{
if(m_passage[sem][0].GetCheck())
{
count1++;
if(m_passage[sem][1].GetCheck())
{
deftempo+="3";
count2++;
}
else
{
deftempo +="1";
}
}
else
{
if(m_passage[sem][1].GetCheck())
{
count2++;
if(m_passage[sem][0].GetCheck())
{
deftempo+="3";
count1++;
}
else
{
deftempo +="2";
}
}
// pas de passage pour cette semaine
else
{
deftempo +="0";
}
}
}
// le tempo est il équilibré?
// oui on l'ajoute
if(count1==count2)
{
tempo.m_Libelle = libelle;
tempo.m_periode = m_periode.GetCurSel()+1;
tempo.m_Definition = deftempo;
// mise à jour du tempo
m_TableTempo.SetAt(m_indexTableTempo,tempo);
m_TableTempo.SetModified(1);
// modification de la base
}
else
{
MessageBox(" Tempo invalide:\nLe tempo doit contenir le même nombre de passages\n sur les deux demi-park");
return;
}
}
EndDialog(IDOK);
}
void CDlgModifTempo::OnAnnuler()
{
EndDialog(IDCANCEL);
}
BOOL CDlgModifTempo::OnInitDialog()
{
CDialog::OnInitDialog();
// Ajout des libellés tempos dans la liste
int size = m_TableTempo.GetSize();
for(int tempo=0;tempo<size;tempo++)
{
CString libelle = m_TableTempo.GetLibelle(tempo);
m_ListTempo.AddString(libelle);
}
// libellé limité à dix caractères
m_libtempo.SetLimitText(10);
// ajout des périodes à la combo: max 10 semaines
CString chaine;
for(int periode=1;periode<10;periode++)
{
chaine.Format("%d",periode);
m_periode.AddString(chaine);
}
// ajout des boutons de passage au tableau
CWnd * fenetre = m_passage11.FromHandle(m_passage11);
m_passage[0][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage12);
m_passage[0][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage21);
m_passage[1][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage22);
m_passage[1][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage31);
m_passage[2][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage32);
m_passage[2][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage41);
m_passage[3][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage42);
m_passage[3][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage51);
m_passage[4][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage52);
m_passage[4][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage61);
m_passage[5][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage62);
m_passage[5][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage71);
m_passage[6][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage72);
m_passage[6][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage81);
m_passage[7][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage82);
m_passage[7][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage91);
m_passage[8][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage92);
m_passage[8][1].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage101);
m_passage[9][0].m_hWnd = fenetre->m_hWnd;
fenetre = m_passage11.FromHandle(m_passage102);
m_passage[9][1].m_hWnd = fenetre->m_hWnd;
UpdateData(0);
return TRUE;
}
// le tempo change, on affiche le libellé et les passages associés
void CDlgModifTempo::OnSelchangeListtempo()
{
CString libelle;
m_ListTempo.GetText(m_ListTempo.GetCurSel(),libelle);
m_indexTableTempo = theApp.IndexTempoDuLibelle(libelle);
// récupération du libellé
m_libtempo.SetWindowText(libelle);
m_OldLibelleTempo=libelle;
// récupération de la période
tagTempo tempo = m_TableTempo.GetAt(m_indexTableTempo);
m_periode.SetCurSel(tempo.m_periode-1);
// période active
for(int sem=0;sem<10;sem++)
{
if(sem<=(tempo.m_periode-1))
{
m_passage[sem][0].EnableWindow(1);
m_passage[sem][1].EnableWindow(1);
}
else
{
m_passage[sem][0].EnableWindow(0);
m_passage[sem][1].EnableWindow(0);
}
// mise à zéro des passages
m_passage[sem][0].SetCheck(0);
m_passage[sem][1].SetCheck(0);
}
// récupération des passages
for(sem=0;sem<=tempo.m_periode-1;sem++)
{
if(tempo.m_Definition[sem]=='1')
{
m_passage[sem][0].SetCheck(1);
}
else
{
if(tempo.m_Definition[sem]=='2')
{
m_passage[sem][1].SetCheck(1);
}
else if(tempo.m_Definition[sem]=='3')
{
m_passage[sem][0].SetCheck(1);
m_passage[sem][1].SetCheck(1);
}
}
}
}
// Désactive la sélection des tempos lorsque celui-ci est modifié
void CDlgModifTempo::OnChangeTempo()
{
// y a t'il une sélection
if(m_libtempo.GetModify())
{
if(m_ListTempo.IsWindowEnabled())m_ListTempo.EnableWindow(0);
}
}
void CDlgModifTempo::OnSelchangeComboperiode()
{
if(m_ListTempo.GetCurSel()!=LB_ERR)
{
if(m_ListTempo.IsWindowEnabled())m_ListTempo.EnableWindow(0);
}
for(int sem=0;sem<m_periode.GetCurSel()+1;sem++)
{
m_passage[sem][0].EnableWindow(1);
m_passage[sem][1].EnableWindow(1);
}
// effacement des passages pour la post-période
for(sem=m_periode.GetCurSel()+1;sem<10;sem++)
{
m_passage[sem][0].EnableWindow(0);
m_passage[sem][1].EnableWindow(0);
m_passage[sem][0].SetCheck(0);
m_passage[sem][1].SetCheck(0);
}
}
int CDlgModifTempo::IsPassage()
{
for(int sem=0;sem<10;sem++)
{
if((m_passage[sem][0].GetCheck())||(m_passage[sem][1].GetCheck()))
{
return(1);
}
}
return(0);
}
void CDlgModifTempo::OnPaint()
{
CPaintDC dc(this); // device context for painting
CBrush fond(RGB_BleuJFC);
CRect rect;
GetClientRect(&rect);
dc.FillRect(rect,&fond);
}
|
efd15f8168c981798878b6bc4be2cc61c88f7d8e | 74047acaaa68f17daa0bb05a61bd555ff7a86cc5 | /book-lib/jni/mylib/htmlcxx/profile.h | 1ef76407c1b83f1239aefb11da90a481da8ebb05 | [] | no_license | norven63/dreambook_android | 4c7897b4193d32fd688f3dcb095813d761671575 | 7a2f49b7bf6ef20e443d083e2c0dad7a599e353a | refs/heads/master | 2021-01-02T08:47:30.136982 | 2015-06-30T09:53:44 | 2015-06-30T09:53:44 | 20,084,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,151 | h | profile.h | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* This file is part of htmlcxx -- A simple non-validating css1 and html parser
* written in C++.
*
* htmlcxx is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* htmlcxx 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with htmlcxx. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2005-2010 Davi de Castro Reis and Robson Braga Araújo
* Copyright 2011 David Hoerl
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef __MY_PROFILE__
#define __MY_PROFILE__
#ifdef PROFILE
#include <iostream>
#include <iomanip>
#include <sys/time.h>
#define USEC_PER_SEC 1000000
static void __time_val_add(struct timeval *time_, long microseconds)
{
if (microseconds >= 0)
{
time_->tv_usec += microseconds % USEC_PER_SEC;
time_->tv_sec += microseconds / USEC_PER_SEC;
if (time_->tv_usec >= USEC_PER_SEC)
{
time_->tv_usec -= USEC_PER_SEC;
time_->tv_sec++;
}
}
else
{
microseconds *= -1;
time_->tv_usec -= microseconds % USEC_PER_SEC;
time_->tv_sec -= microseconds / USEC_PER_SEC;
if (time_->tv_usec < 0)
{
time_->tv_usec += USEC_PER_SEC;
time_->tv_sec--;
}
}
}
#define PROFILE_DECLARE_STATIC(x) static struct timeval __profile_start##x = {0,0}, __profile_total##x = {0,0}, __profile_end##x = {0,0};
#define PROFILE_DECLARE(x) struct timeval __profile_start##x = {0,0}, __profile_total##x = {0,0}, __profile_end##x = {0,0};
#define PROFILE_START(x) do { gettimeofday(&__profile_start##x, NULL); } while(0);
#define PROFILE_END(x) do { gettimeofday(&__profile_end##x, NULL); } while(0);
#define PROFILE_ADD(x) do { if(!(__profile_end##x.tv_sec > __profile_start##x.tv_sec || (__profile_end##x.tv_sec == __profile_start##x.tv_sec && __profile_end##x.tv_usec >= __profile_start##x.tv_usec))) {\
break;\
}\
__time_val_add(&(__profile_total##x), (__profile_end##x.tv_sec - __profile_start##x.tv_sec)*USEC_PER_SEC);\
__time_val_add(&(__profile_total##x), __profile_end##x.tv_usec);\
__time_val_add(&(__profile_total##x), __profile_start##x.tv_usec * -1);\
} while(0);
#define PROFILE_END_ADD(x) do { PROFILE_END(x); PROFILE_ADD(x); } while(0);
#define PROFILE_CLEAR(x) do { __profile_start##x.tv_sec = 0, __profile_start##x.tv_usec = 0, __profile_total##x.tv_sec = 0, __profile_total##x.tv_usec = 0, __profile_end##x.tv_sec = 0, __profile_end##x.tv_usec = 0; } while(0);
#define __PROFILE_PRINT(prefix, stream, timeval) do {\
int microsec = 0;\
int sec = 0;\
int min = 0;\
int hour = 0;\
/*assert(timeval.tv_sec >= 0);*/\
hour = timeval.tv_sec / 3600;\
min = (timeval.tv_sec % 3600)/60;\
sec = timeval.tv_sec % 60;\
microsec = timeval.tv_usec;\
stream << prefix;\
stream << hour << "h" << min << "m" << sec << "s " << microsec << " microseconds";\
} while (0);
#define PROFILE_PRINT(x, prefix, stream) __PROFILE_PRINT(prefix, stream, __profile_total##x)
#define PROFILE_PRINT_CURRENT(x, prefix, stream) do {\
struct timeval sum;\
sum.tv_sec = 0;\
sum.tv_usec = 0;\
if(!(__profile_end##x.tv_sec > __profile_start##x.tv_sec || (__profile_end##x.tv_sec == __profile_start##x.tv_sec && __profile_end##x.tv_usec >= __profile_start##x.tv_usec))) {\
fprintf(stderr, "Refusing to print invalid profile measure\n");\
break;\
}\
__time_val_add(&sum, (__profile_end##x.tv_sec - __profile_start##x.tv_sec)*1000000);\
__time_val_add(&sum, __profile_end##x.tv_usec);\
__time_val_add(&sum, __profile_start##x.tv_usec * -1);\
__PROFILE_PRINT(prefix, stream, sum);\
} while(0);
#define PROFILE_PRINT_CURRENT_NL(x, prefix, stream) do {\
PROFILE_PRINT_CURRENT(x, prefix, stream);\
stream << std::endl;\
} while(0);
#define PROFILE_PRINT_NL(x, prefix, stream) do {\
PROFILE_PRINT(x, prefix, stream);\
stream << std::endl;\
} while(0);
#else
#define PROFILE_DECLARE(x)
#define PROFILE_DECLARE_STATIC(x)
#define PROFILE_START(x)
#define PROFILE_END(x)
#define PROFILE_ADD(x)
#define PROFILE_END_ADD(x)
#define PROFILE_PRINT(x, prefix, stream)
#define PROFILE_PRINT_NL(x, prefix, stream)
#define PROFILE_PRINT_CURRENT(x, prefix, stream)
#define PROFILE_PRINT_CURRENT_NL(x, prefix, stream)
#define PROFILE_CLEAR(x)
#endif
#endif //__MY_PROFILE__
/*
fprintf(stderr, "Profiler ignoring invalid time measure from %d@%s\n", __LINE__, __FILE__);\
fprintf(stderr, "End: sec %u usec %u Start: sec %u usec %u\n", __profile_end##x.tv_sec, __profile_end##x.tv_usec, __profile_start##x.tv_sec, __profile_start##x.tv_usec);\
*/
|
f3d8efe428c25602b908eae75b29bf7e69c63e90 | 6d1fe21e452bc758a5463fd522ea9160d54d0683 | /source/greatest_common_divisor.hpp | b4cac49bfad2e63bdccaed39a9d747c453939412 | [
"MIT"
] | permissive | pawel-kieliszczyk/algorithms | 90662189d963fbb72c3929599327791141e7fe40 | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | refs/heads/master | 2021-01-02T09:15:16.950845 | 2019-03-31T19:20:54 | 2019-03-31T19:20:54 | 26,922,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 317 | hpp | greatest_common_divisor.hpp | #ifndef PK_GREATESTCOMMONDIVISOR_HPP
#define PK_GREATESTCOMMONDIVISOR_HPP
namespace pk
{
template<class T>
T greatest_common_divisor(T a, T b)
{
while(b > 0)
{
const T tmp = b;
b = a % b;
a = tmp;
}
return a;
}
} // namespace pk
#endif // PK_GREATESTCOMMONDIVISOR_HPP
|
e0565bf01e8c08cfe9c34b844961dfa13d8e2c03 | ecb3b5552115c0228239a1bf7edb7a127de57482 | /cameronet/include/cameronet.h | 94a4e607017ac06ec130883bbca3f708d5f349c7 | [] | no_license | yyyly/l110 | e8edfbab9600e1e154c8cec6d8220ed5ecbf5978 | 3361876192994b5a3ad906c5c0753ddbf19a0362 | refs/heads/master | 2020-09-28T01:58:41.569957 | 2020-08-22T02:16:54 | 2020-08-22T02:16:54 | 226,661,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,297 | h | cameronet.h | #ifndef CAMERONET_H
#define CAMERONET_H
#include<QString>
#include<QMap>
#include<QList>
#include<QObject>
#include "HCNetSDK.h"
#include "cameronet_global.h"
#include "enums.h"
struct CameraDeviceImf
{
Camero::Mold mold; //设备厂家
QString name; //设备名称
QString ip; //设备的IP地址
unsigned short port; //设备端口号
QString accoumt; //设备账户
QString passWord; //访问密码
Camero::TYPE type; //设备种类(路线机,摄像头)
int channalAmount; //(通道号)
QMap<int,QString> channelNameMap; //设备的通道名称
LONG luserId; //设备登陆后的句柄
LONG playId; //播放句柄
DWORD LoginWarming; //登陆时错误码
DWORD playWarming; //播放时错误码
friend bool operator ==(const CameraDeviceImf &,const CameraDeviceImf &);
};
inline bool operator == (const CameraDeviceImf &imf1,const CameraDeviceImf &imf2)
{
return imf1.name == imf2.name &&
imf1.mold == imf2.mold &&
imf1.ip == imf2.ip &&
imf1.port == imf2.port&&
imf1.type == imf2.type;
}
class CAMERONETSHARED_EXPORT CameroNet : public QObject
{
Q_OBJECT
public:
/*构造函数需实现单列模式*/
explicit CameroNet(QObject *p =nullptr);
~CameroNet();
/*登陆函数*/
void login(CameraDeviceImf &i);
/*播放函数,默认采用主码流,TCP连接方式*/
LONG realPlay(CameraDeviceImf *info, LONG channel,HWND playWnd);
/*停止播放,函数的错误信息留给调用模块处理*/
DWORD stopPlay(CameraDeviceImf *info);
/*登出,函数的错误信息留给调用模块处理*/
DWORD loginOut(CameraDeviceImf *info);
/*抓图函数*/
DWORD capPic(CameraDeviceImf *info,const QString ficAdd);
/*声音控制函数*/
DWORD opendSound(CameraDeviceImf *info);
DWORD closeSound(CameraDeviceImf *info);
signals:
void signalDeviceStatusChanged();
protected:
bool event(QEvent *event);
private:
static void CALLBACK hkLoginResutCallback(LONG lUserID,DWORD dwResult,
LPNET_DVR_DEVICEINFO_V30 lpDeviceInfo,void *pUser);
static QList<CameraDeviceImf *> HKPinfoList;//存储登陆信息,析构函数使用
};
#endif // CAMERONET_H
|
b9f70b7c260310a364b23e91fafd4df22a0cb0a9 | a55cd27ed328c3ceaf5f54325e31088fdef42c09 | /files/include/sead/framework/seadTaskMgr.h | 7b1422cf8cf31d2796afefe14af96d883807c747 | [] | no_license | aboood40091/NSMBU-haxx | e8762fab7d703956cc642623cbc4a86fd4d3fca5 | 63a0eda0fae9ad741491452927f57dd33a37acd5 | refs/heads/master | 2023-06-11T20:41:01.232252 | 2023-06-03T07:36:48 | 2023-06-03T07:36:48 | 184,704,040 | 145 | 6 | null | 2021-08-04T19:03:49 | 2019-05-03T05:38:06 | C++ | UTF-8 | C++ | false | false | 7,549 | h | seadTaskMgr.h | #ifndef SEAD_TASKMGR_H_
#define SEAD_TASKMGR_H_
#include <framework/seadHeapPolicies.h>
#include <framework/seadMethodTree.h>
#include <framework/seadTaskBase.h>
#include <heap/seadHeapMgr.h>
#include <thread/seadCriticalSection.h>
namespace sead {
class DelegateThread;
class Framework;
class Heap;
class NullFaderTask;
class TaskMgr
{
public:
struct InitializeArg
{
public:
InitializeArg(const TaskBase::CreateArg& roottask_arg)
: create_queue_size(0x20)
, prepare_stack_size(0x8000)
, prepare_priority(-1)
, roottask_create_arg(roottask_arg)
, heap(NULL)
, parent_framework(NULL)
{
}
u32 create_queue_size;
u32 prepare_stack_size;
s32 prepare_priority;
const TaskBase::CreateArg& roottask_create_arg;
Heap* heap;
Framework* parent_framework;
};
#ifdef cafe
static_assert(sizeof(InitializeArg) == 0x18, "sead::TaskMgr::InitializeArg size mismatch");
#endif // cafe
class TaskCreateContextMgr;
public:
TaskMgr(const InitializeArg& arg);
void appendToList_(TaskBase::List& ls, TaskBase* task);
bool changeTaskState_(TaskBase* task, TaskBase::State state);
void destroyTaskSync(TaskBase* task);
void doDestroyTask_(TaskBase* task);
void finalize();
CriticalSection mCriticalSection;
Framework* mParentFramework;
DelegateThread* mPrepareThread;
NullFaderTask* mNullFaderTask;
TaskBase::List mPrepareList;
TaskBase::List mPrepareDoneList;
TaskBase::List mActiveList;
TaskBase::List mStaticList;
TaskBase::List mDyingList;
TaskBase::List mDestroyableList;
HeapArray mHeapArray;
TaskCreateContextMgr* mTaskCreateContextMgr;
u32 mMaxCreateQueueSize;
TaskBase* mRootTask;
TaskBase::CreateArg mRootTaskCreateArg;
TaskMgr::InitializeArg mInitializeArg;
MethodTreeNode mCalcDestructionTreeNode;
u32 _1a0;
u32 _1a4;
};
#ifdef cafe
static_assert(sizeof(TaskMgr) == 0x1A8, "sead::TaskMgr size mismatch");
#endif // cafe
} // namespace sead
#define SEAD_TASK_SINGLETON_DISPOSER(CLASS) \
public: \
static CLASS* instance() { return sInstance; } \
static void setInstance_(sead::TaskBase* instance); \
static void deleteInstance(); \
\
protected: \
class SingletonDisposer_ \
{ \
public: \
SingletonDisposer_() : mIsSetAsSingleton_(false) { } \
~SingletonDisposer_(); \
\
bool mIsSetAsSingleton_; \
}; \
\
private: \
CLASS(const CLASS&); \
const CLASS& operator=(const CLASS&); \
\
protected: \
SingletonDisposer_ mSingletonDisposer_; \
\
static CLASS* sInstance; \
\
friend class SingletonDisposer_;
#define SEAD_TASK_SET_SINGLETON_INSTANCE(CLASS) \
void CLASS::setInstance_(sead::TaskBase* instance) \
{ \
if (CLASS::sInstance == NULL) \
{ \
CLASS::sInstance = static_cast<CLASS*>(instance); \
static_cast<CLASS*>(instance)->mSingletonDisposer_.mIsSetAsSingleton_ = true; \
} \
else \
{ \
/*SEAD_ASSERT_MSG(false, "Create Singleton Twice (%s) : addr %x", "CLASS", CLASS::sInstance);*/ \
} \
}
#define SEAD_TASK_DELETE_SINGLETON_INSTANCE(CLASS) \
void CLASS::deleteInstance() \
{ \
if (CLASS::sInstance != NULL) \
{ \
CLASS::sInstance->mTaskMgr->destroyTaskSync(CLASS::sInstance); \
CLASS::sInstance = NULL; \
} \
}
#define SEAD_TASK_SINGLETON_DISPOSER_IMPL(CLASS) \
CLASS* CLASS::sInstance = NULL; \
\
SEAD_TASK_SET_SINGLETON_INSTANCE(CLASS) \
SEAD_TASK_DELETE_SINGLETON_INSTANCE(CLASS) \
\
CLASS::SingletonDisposer_::~SingletonDisposer_() \
{ \
if (mIsSetAsSingleton_) \
{ \
CLASS::sInstance = NULL; \
} \
}
#endif // SEAD_TASKMGR_H_
|
943aca1896afc2bbc385c4d4abf3362ada6691fe | 278064e26e76d5313f99a738ac26b3406327fce3 | /stephanWolfTrends.cpp | 646a46539db18fe768224d98fa5b486202cb161e | [] | no_license | XCCOOP/Zeitgeist | bf818df24fb896977b108b2017886ccb47abfad4 | c8ec2d457edddaebabc06a8f1d78d130180c5976 | refs/heads/master | 2021-01-18T01:47:42.167600 | 2014-11-25T16:28:50 | 2014-11-25T16:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp | stephanWolfTrends.cpp | #include "stephanWolfTrends.h"
void stephanWolfTrends::increaseCount(std::string s, unsigned int amount) {
bool alreadyExists = false;
for(unsigned int i = 0; i < wordCountTable.size(); i++) {
if(wordCountTable[i].first = s) {
wordCountTable[i].second + amount;
alreadyExists = true;
}
}
if(alreadyExists == false) {
wordCountTable.insert(s, amount);
}
}
unsigned int stephanWolfTrends::numEntries(){
return wordCountTable.size();
}
unsigned int stephanWolfTrends::getCount(std::string s){
//Check to see if word is present
for (unsigned int i = 0; i < wordCountTable.size(); i++){
if (wordCountTable[i].first == s){
//If so, return the count
return wordCountTable[i].second;
}
}
//otherwise, return 0
return 0;
}
std::string stephanWolfTrends::getNthPopular(unsigned int n){
if (n <= numEntries()){
return wordCountVector[n].second;
}
//If they give bad input, return empty string.
return "";
} |
2dd165ad80426181ef50f4080043433fe6bbcc26 | 6fe17c32ba5bb492e276e13128c516a3f85f01ff | /New folder/796B. Find The Bone.cpp | 0bfc0e14f696a7d71531bd4a455a72ad9fe2e4f7 | [
"Apache-2.0"
] | permissive | YaminArafat/Codeforces | 35c5c527c8edd51c7f591bfe6474060934241d86 | 3d72ba0b5c9408a8e2491b25b5b643e9f9be728b | refs/heads/master | 2023-08-17T03:12:04.596632 | 2021-10-06T14:49:29 | 2021-10-06T14:49:29 | 351,042,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | 796B. Find The Bone.cpp | #include <bits/stdc++.h>
using namespace std;
bool mp[1000006];
int main()
{
int n,m,k,u,v,init=1,ans=-5,x;
scanf("%d %d %d",&n,&m,&k);
for(int i=0;i<m;i++)
{
scanf("%d",&x);
mp[x]=1;
}
for(int i=0;i<k;i++)
{
scanf("%d %d",&u,&v);
if(u==init)
{
if(!mp[u])
init=v;
else
ans=u;
}
else if(v == init)
{
if(!mp[v])
init=u;
else
ans=v;
}
}
if(ans<0)
ans=init;
printf("%d\n",ans);
}
|
8bee4158a0091adc6c5a3c60b0d6cf612359fa4d | 8121ed9d8fed6078b763bdf49d427a58ddc38b12 | /1181.cpp | a08bf6643d319d470e675bda7359a76549381075 | [] | no_license | jkjan/Baekjoon | e6e2663eb567c470cb3ce78d7e80a17763a8a1ff | e5cd2ba8bdd91234cce82e6c1cd9a4ae169478da | refs/heads/master | 2022-12-18T01:00:27.002673 | 2020-09-13T13:01:59 | 2020-09-13T13:01:59 | 293,594,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 701 | cpp | 1181.cpp | #include <iostream>
#include <set>
using namespace std;
typedef struct word {
string w;
}word;
void input(int* N, set<word>* words);
void output(set<word>* words);
int main() {
int N;
set<word> words;
input(&N, &words);
output(&words);
return 0;
}
bool operator<(const word& a, const word& b) {
if (a.w.length() == b.w.length()) {
return a.w < b.w;
}
return (a.w.length() < b.w.length());
}
void input(int* N, set<word>* words) {
cin >> *N;
for (int i = 0; i < *N; i++) {
string a;
cin >> a;
words->insert({a});
}
}
void output(set<word>* words) {
for (auto & s : *words) {
cout << s.w << endl;
}
} |
59006246c232541cd38bc1c8afcc6a94321141cc | dbef9fa1e78187bf06df4f9b25f3e19fc28638b5 | /src/Cmd/Cmder.hpp | 8187313d3338bf1f88cdcc2786f8771326141613 | [] | no_license | YigaoFan/RPC | dd9001bb59669c0dacd0fea413e2b3fb0616d777 | dd8dea093fc1c5e7907f27d74bd61fb96deafd62 | refs/heads/master | 2023-03-20T04:52:46.911602 | 2021-03-11T07:00:43 | 2021-03-11T07:00:43 | 158,654,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,874 | hpp | Cmder.hpp | #pragma once
#include <array>
#include <vector>
#include <string>
#include <asio.hpp>
#include <string_view>
#include "StringMatcher.hpp"
#include "../Server/CmdFunction.hpp"
#include "../Network/Socket.hpp"
#include "../TestFrame/Util.hpp"
using namespace Test;
namespace Cmd
{
using Network::Socket;
using Server::GetCmdsName;
using Server::ProcessCmd;
using ::std::array;
using ::std::move;
using ::std::string;
using ::std::string_view;
using ::std::vector;
// 运行命令,出异常了不要让程序停止,其他情况异常要抛出去
class Cmder
{
private:
StringMatcher _cmdMatcher;
Socket _socket;
public:
static Cmder NewFrom(Socket connectedSocket)
{
vector<string> cmds = GetCmdsName();
cmds.push_back("exit"); // 这里稍有点不好,或许可以提供给外部注册进来
return Cmder(StringMatcher(move(cmds)), move(connectedSocket));
}
Cmder(StringMatcher cmdMatcher, Socket connectedSocket)
: _cmdMatcher(move(cmdMatcher)), _socket(move(connectedSocket))
{ }
/// return maybe multiple lines
vector<string> Run(string cmd)
{
// 这里可以从哪获取一点被调用接口的信息然后进行提示和检查
// 使用一些代码去生成
auto [requests, responseProcessor] = ProcessCmd(cmd);
// log("start send\n");
// 1. 首先解析没有报错
// 2. 其次为什么两次的内容合成一个了
for (auto& r : requests)
{
// log("send %s\n", r.c_str());
_socket.Send(r);
}
// log("start receive\n");
auto id = _socket.Receive();
// log("receive id %s\n", id.c_str());
auto response = _socket.Receive();
// log("receive response %s\n", response.c_str());
return responseProcessor(response);
}
/// return is multiple options
vector<string> Complete(string_view partKeyword)
{
return _cmdMatcher.Match(partKeyword);
}
};
}
|
65db9c5ddb3ced1568013a5b0df8840c058a78a4 | bda8f1eb9b8ea92387c38be585e4f34f963ed769 | /1153.cpp | 8549fca55e93df10ad871978372d6c58db2ab172 | [] | no_license | rafabm90/URI-Exercise | d267789a6251a50c373e7fb8349da1b165f60e33 | d3e69071bce7b4b9161a45ededa8ffeb27c00d32 | refs/heads/master | 2023-03-26T01:37:53.883149 | 2021-03-25T12:37:42 | 2021-03-25T12:37:42 | 348,078,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | 1153.cpp | /*
by:Rafael Borges Morais
*/
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, fat = 1;
cin >> n;
for(int i = 1; i <= n;i++){
fat = fat*i;
}
cout << fat << endl;
} |
4f4e0a810f87384fa2032cb60ba641897e33d04a | 983cbd0fb2d3f4f9a76e2cfe4d1ae7c1e3beb257 | /test/map.cpp | 11f0534ea1432ed34421b58a7b81332d350035ba | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | ATGsan/trie | 728ac8e8434fbe812f062c86d352a3d104a7fcbc | 32af51673551b5c345a986f28ecd4ad3eb832d61 | refs/heads/master | 2023-05-11T19:15:34.537054 | 2023-05-06T11:32:47 | 2023-05-06T11:32:47 | 635,700,175 | 0 | 0 | BSL-1.0 | 2023-05-06T11:32:48 | 2023-05-03T09:11:59 | null | UTF-8 | C++ | false | false | 10,173 | cpp | map.cpp | #include <boost/core/lightweight_test.hpp>
#include "boost/trie/trie_map.hpp"
//multi include test
#include "boost/trie/trie_map.hpp"
#include "boost/trie/trie.hpp"
#include <string>
typedef boost::tries::trie_map<char, int> tmci;
typedef tmci::iterator ti;
typedef tmci::const_iterator tci;
typedef tmci::reverse_iterator tri;
typedef tmci::const_reverse_iterator tcri;
void operator_test()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s2 = "bbb";
t[s] = 1;
BOOST_TEST(t[s] == 1);
t[s] = 2;
BOOST_TEST(t[s] == 2);
t[s2] = t[s];
BOOST_TEST(t[s] == t[s2]);
}
void insert_and_find_test()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = 1;
BOOST_TEST((*t.find(s)).second == 1);
BOOST_TEST(t.find(s) != t.end());
BOOST_TEST(t.find(s2) == t.end());
BOOST_TEST(t.find(s2) == t.end());
t[s] = 2;
BOOST_TEST((*t.find(s)).second == 2);
t[s2] = t[s];
BOOST_TEST(t.find(s2) != t.end());
BOOST_TEST(t.find(s1) == t.find(s3));
BOOST_TEST(t.find(s) != t.find(s2));
BOOST_TEST((t.insert(s1, 3).second == true));
BOOST_TEST((t.insert(s3, 10).second == true));
BOOST_TEST((t.insert(s2, 10)).second == false);
BOOST_TEST((t.insert(s, 10)).second == false);
}
void copy_test()
{
boost::tries::trie_map<char, int> t, t2;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = 1; t[s1] = 2; t[s2] = 3; t[s3] = 4;
t2 = t;
BOOST_TEST(t2.size() == 4);
BOOST_TEST(t2.count_node() == 8);
BOOST_TEST(t2[s] == 1);
BOOST_TEST(t2[s1] == 2);
BOOST_TEST(t2[s2] == 3);
BOOST_TEST(t2[s3] == 4);
boost::tries::trie_map<char, int> t3(t2);
BOOST_TEST(t3.size() == 4);
BOOST_TEST(t3.count_node() == 8);
BOOST_TEST((*t3.find(s)).second == 1);
BOOST_TEST((*t3.find(s1)).second == 2);
BOOST_TEST((*t3.find(s2)).second == 3);
BOOST_TEST((*t3.find(s3)).second == 4);
t3[std::string("a")] = 10;
BOOST_TEST(t3.size() == 5);
BOOST_TEST(t3.count_node() == 8);
BOOST_TEST((*t3.begin()).second == 10);
}
void iterator_operator_plus()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
BOOST_TEST(t.empty() == true);
BOOST_TEST(t.size() == 0);
BOOST_TEST(t.begin() == t.end());
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
BOOST_TEST(t.begin() != t.end());
boost::tries::trie_map<char, int>::iterator i;
i = t.begin();
BOOST_TEST((*i).second == 1);
++i;
BOOST_TEST((*i).second == 2);
BOOST_TEST(t[s2] == 3);
++i;
BOOST_TEST((*i).second == 3);
++i;
BOOST_TEST(i == t.end());
++i;
BOOST_TEST(i == t.end());
}
void iterator_operator_minus()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
boost::tries::trie_map<char, int>::iterator i;
boost::tries::trie_map<char, int>::const_iterator ci(t.end());
BOOST_TEST(t.empty() == true);
BOOST_TEST(t.size() == 0);
i = t.begin();
BOOST_TEST(i == t.end());
++i;
BOOST_TEST(i == t.end());
++i;
BOOST_TEST(i == t.end());
--i;
BOOST_TEST(i == t.end());
--i;
BOOST_TEST(i == t.end());
ci = t.begin();
BOOST_TEST(ci == t.end());
++ci;
BOOST_TEST(ci == t.end());
++ci;
BOOST_TEST(ci == t.end());
--ci;
BOOST_TEST(ci == t.end());
--ci;
BOOST_TEST(ci == t.end());
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
BOOST_TEST(t.begin() != t.end());
i = t.begin();
BOOST_TEST((*i).second == 1);
(*i).second= 10;
BOOST_TEST((*i).second == 10);
ci = t.begin();
BOOST_TEST((*ci).second == 10);
--i;
BOOST_TEST(i == t.begin());
BOOST_TEST(t[s2] == 3);
i = t.end();
--i;
BOOST_TEST((*i).second == 3);
t[s3] = 4;
++i;
BOOST_TEST((*i).second == 4);
++i;
BOOST_TEST(i == t.end());
++i;
BOOST_TEST(i == t.end());
--i;
BOOST_TEST((*i).second == 4);
BOOST_TEST(t.count_node() == 8);
BOOST_TEST(t.size() == 4);
}
void reverse_iterator_operator_plus()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
BOOST_TEST(t.empty() == true);
BOOST_TEST(t.size() == 0);
BOOST_TEST(t.begin() == t.end());
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
BOOST_TEST(t.begin() != t.end());
tcri i;
i = t.rbegin();
BOOST_TEST((*i).second == 3);
--i;
BOOST_TEST((*i).second == 3);
++i;
BOOST_TEST((*i).second == 2);
BOOST_TEST(t[s2] == 3);
++i;
BOOST_TEST((*i).second == 1);
++i;
BOOST_TEST(i == t.rend());
++i;
BOOST_TEST(i == t.rend());
}
void reverse_iterator_operator_minus()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
tri i;
tcri ci;
BOOST_TEST(t.empty() == true);
BOOST_TEST(t.size() == 0);
i = t.rbegin();
BOOST_TEST(i == t.rend());
++i;
BOOST_TEST(i == t.rend());
++i;
BOOST_TEST(i == t.rend());
--i;
BOOST_TEST(i == t.rend());
--i;
BOOST_TEST(i == t.rend());
ci = t.rbegin();
BOOST_TEST(ci == t.rend());
++ci;
BOOST_TEST(ci == t.rend());
++ci;
BOOST_TEST(ci == t.rend());
--ci;
BOOST_TEST(ci == t.rend());
--ci;
BOOST_TEST(ci == t.rend());
t[s1] = 2;
t[s2] = 3;
BOOST_TEST(t.rbegin() != t.rend());
i = t.rbegin();
BOOST_TEST((*i).second == 3);
(*i).second= 10;
BOOST_TEST((*i).second == 10);
ci = i;
BOOST_TEST((*ci).second == 10);
--ci;
BOOST_TEST(ci == t.rbegin());
t[s3] = 4;
--ci;
BOOST_TEST(ci == t.rbegin());
i = t.rend();
BOOST_TEST(i == t.rend());
ci = --i;
BOOST_TEST((*ci).second == 2);
--ci;
BOOST_TEST((*ci).second == 10);
--ci;
BOOST_TEST((*ci).second == 4);
--ci;
BOOST_TEST((*ci).second == 4);
++ci;
BOOST_TEST((*ci).second == 10);
++ci;
BOOST_TEST((*ci).second == 2);
++ci;
BOOST_TEST(ci == t.rend());
++ci;
BOOST_TEST(ci == t.rend());
--ci;
BOOST_TEST((*ci).second == 2);
++ci;
BOOST_TEST(ci == t.rend());
t[s] = 1;
BOOST_TEST(ci != t.rend());
BOOST_TEST((*ci).second == 1);
++ci;
BOOST_TEST(ci == t.rend());
BOOST_TEST((*ci).second == 1);
++ci;
BOOST_TEST(ci == t.rend());
BOOST_TEST(t.count_node() == 8);
BOOST_TEST(t.size() == 4);
}
void clear()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = t[s1] = t[s2] = t[s3] = 10;
size_t node_cnt = t.count_node();
BOOST_TEST(t.size() == 4);
BOOST_TEST(t.count_node() == node_cnt);
t.clear();
BOOST_TEST(t.size() == 0);
BOOST_TEST(t.count_node() == 0);
BOOST_TEST(t[s] == 0);
BOOST_TEST(t.size() == 1);
BOOST_TEST(t.count_node() == 3);
}
void erase_iterator()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
t[s3] = 4;
size_t node_cnt = t.count_node();
BOOST_TEST(t.size() == 4);
BOOST_TEST(t.count_node() == node_cnt);
boost::tries::trie_map<char, int>::iterator i;
i = t.begin();
t.erase(t.begin());
i = t.begin();
BOOST_TEST(t.size() == 3);
BOOST_TEST(t.count_node() == 8);
BOOST_TEST((*i).second == 2);
t.erase(i);
BOOST_TEST(t.size() == 2);
i = t.begin();
BOOST_TEST((*i).second == 3);
BOOST_TEST(t.count_node() == 6);
BOOST_TEST(t[s] == 0);
i = t.begin();
BOOST_TEST(t.size() == 3);
BOOST_TEST((*i).second == 0);
BOOST_TEST(t.count_node() == 7);
}
void erase_key()
{
boost::tries::trie_map<char, int> t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
t[s3] = 4;
size_t node_cnt = t.count_node();
BOOST_TEST(t.size() == 4);
BOOST_TEST(t.count_node() == node_cnt);
boost::tries::trie_map<char, int>::iterator i;
i = t.begin();
t.erase(s);
i = t.begin();
BOOST_TEST(t.size() == 3);
BOOST_TEST(t.count_node() == 8);
BOOST_TEST((*i).second == 2);
t.erase(s1);
BOOST_TEST(t.size() == 2);
i = t.begin();
BOOST_TEST((*i).second == 3);
BOOST_TEST(t.count_node() == 6);
BOOST_TEST(t[s] == 0);
i = t.begin();
BOOST_TEST(t.size() == 3);
BOOST_TEST((*i).second == 0);
BOOST_TEST(t.count_node() == 7);
t.erase(std::string("bababa"));
i = t.begin();
BOOST_TEST(t.size() == 3);
BOOST_TEST((*i).second == 0);
BOOST_TEST(t.count_node() == 7);
}
void find_prefix()
{
tmci t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
t[s3] = 4;
tmci::iterator_range r = t.find_prefix(std::string("a"));
BOOST_TEST((*r.second).second == 4);
int j = 1;
for (tmci::iterator i = r.first; i != r.second; ++i)
{
BOOST_TEST((*i).second == j);
++j;
}
r = t.find_prefix(std::string("aa"));
BOOST_TEST((*r.second).second == 4);
j = 1;
for (tmci::iterator i = r.first; i != r.second; ++i)
{
BOOST_TEST((*i).second == j);
++j;
}
r = t.find_prefix(std::string("aaa"));
BOOST_TEST((*r.second).second == 3);
j = 1;
for (tmci::iterator i = r.first; i != r.second; ++i)
{
BOOST_TEST((*i).second == j);
++j;
}
r = t.find_prefix(std::string("b"));
BOOST_TEST(r.second == t.end());
for (tmci::iterator i = r.first; i != r.second; ++i)
{
BOOST_TEST((*i).second == 4);
}
r = t.find_prefix(std::string("bbbbb"));
BOOST_TEST(r.second == t.end());
for (tmci::iterator i = r.first; i != r.second; ++i)
{
BOOST_TEST((*i).second == 1);
}
}
void get_key_test()
{
tmci t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
t[s3] = 4;
tmci t2;
tmci::iterator i = t.begin();
t2[i.get_key()] = 1;
++i;
t2[i.get_key()] = 2;
++i;
t2[i.get_key()] = 3;
++i;
t2[i.get_key()] = 4;
tmci::iterator j = t2.begin();
for (i = t.begin(); i != t.end(); ++i, ++j)
{
BOOST_TEST(*i == *j);
BOOST_TEST(i.get_key() == j.get_key());
}
j = t2.erase(s2);
BOOST_TEST((*j).second == 4);
}
void get_key_reverse_test()
{
tmci t;
std::string s = "aaa", s1 = "aaaa", s2 = "aab", s3 = "bbb";
t[s] = 1;
t[s1] = 2;
t[s2] = 3;
t[s3] = 4;
tcri i = t.rbegin();
tmci t2;
t2[(*i).first] = 4;
++i;
t2[(*i).first] = 3;
++i;
t2[(*i).first] = 2;
++i;
t2[(*i).first] = 1;
tcri j = t2.rbegin();
for (i = t.rbegin(); i != t.rend(); ++i, ++j)
{
BOOST_TEST(*i == *j);
BOOST_TEST((*i).first == (*j).first);
}
}
int main() {
operator_test();
insert_and_find_test();
copy_test();
iterator_operator_plus();
iterator_operator_minus();
reverse_iterator_operator_plus();
reverse_iterator_operator_minus();
clear();
erase_iterator();
erase_key();
find_prefix();
get_key_test();
get_key_reverse_test();
return boost::report_errors();
}
|
fbc138bf52d6d18a841210fd881199e62f1bbeb1 | b27f9f39dc96243682d0e2ba3b831e20554555a3 | /ACM/2017-2018 Tsukuba/PG.cpp | 0404c97b52bb761ecec932163d3e4e389075ab8a | [] | no_license | ianCK/NoName | 3d3abee5901a2e7207a670d7c9d52c6a12ffbfa3 | 54614b42eec330a13af0fa02d09b6d9d9deb6dba | refs/heads/master | 2020-06-14T18:34:06.111310 | 2019-06-02T13:06:28 | 2019-06-02T13:06:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | cpp | PG.cpp | #include<bits/stdc++.h>
using namespace std;
int ans[2];
const double pi=acos(-1.0);
int flr(double x)
{
if(x>=0)return (int)x;
return (int)x-1;
}
int cal(int deg,int d)
{
double a=1.0*d*cos(deg*pi/180.0);
double b=1.0*d*sin(deg*pi/180.0);
double x=a-b/sqrt(3);
double y=2*b/sqrt(3);
// printf("%.3f %.3f %.3f %.3f\n",a,b,x,y);
// printf("%.3f\n",(x-flr(x))+(y-flr(y)));
if((flr(x)+flr(y))&1)
{
if((flr(x)&1)^((x-flr(x))+(y-flr(y))>1.0))return 2;
else return 1;
}
else
{
if((flr(x)&1)^((x-flr(x))+(y-flr(y))>1.0))return 3;
else return 0;
}
}
int main()
{
for(int i=0;i<2;i++)
{
char c[5];
int degree,dis;
scanf("%s%d%d",c,°ree,&dis);
if(c[0]=='C')degree+=60;
else if(c[0]=='D')degree+=120;
ans[i]=cal(degree,dis);
//printf("ans[%d] = %d\n",i,ans[i]);
}
puts(ans[0]==ans[1] ? "YES" : "NO");
return 0;
}
|
3405f027c8151ee26bf5651648bdcd4ff45c51d6 | f4064dbc68decb87973e0b05992d39268b0c4a1a | /AOJ/ACPC/2015/day3/A.cpp | 9807d0ff36bd8f6244cccc4bc2beb26dab4e7e7b | [] | no_license | odanado/Procon | d7c75387b15e3dc860b6a813eb43b1fa1ab8ffd3 | 6f30fb4819f577df9db54ccc74765eb0ddf2119c | refs/heads/master | 2020-04-12T01:43:42.196994 | 2017-08-06T14:58:02 | 2017-08-06T14:58:02 | 48,416,463 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,977 | cpp | A.cpp | #include <algorithm>
#include <functional>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <bitset>
#include <climits>
#define all(c) (c).begin(), (c).end()
#define rep(i,n) for(int i=0;i<(n);i++)
#define pb(e) push_back(e)
#define mp(a, b) make_pair(a, b)
#define fr first
#define sc second
const int INF=100000000;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
using namespace std;
typedef pair<int ,int > P;
typedef long long ll;
int K;
string iso[101];
string naka[101];
string solve() {
int pow1=0,pow2=0;
rep(i,K) {
if(iso[i]=="tameru") pow1++;
if(naka[i]=="tameru") pow2++;
pow1=min(pow1,5);
pow2=min(pow2,5);
if(iso[i]=="kougekida"&&naka[i]=="kougekida") {
if(pow1==pow2) {
pow1=pow2=0;
continue;
}
else if(pow1<pow2) {
pow1=pow2=0;
return "Nakajima-kun";
}
else {
pow1=pow2=0;
return "Isono-kun";
}
}
if(iso[i]=="kougekida"&&pow1==0) return "Nakajima-kun";
if(naka[i]=="kougekida"&&pow2==0) return "Isono-kun";
if(iso[i]=="kougekida"&&naka[i]=="tameru") {
return "Isono-kun";
}
if(iso[i]=="kougekida"&&naka[i]=="mamoru") {
if(pow1==5) return "Isono-kun";
pow1=0;
}
if(iso[i]=="mamoru"&&naka[i]=="kougekida") {
if(pow2==5) return "Nakajima-kun";
pow2=0;
}
if(iso[i]=="tameru"&&naka[i]=="kougekida") {
return "Nakajima-kun";
}
}
return "Hikiwake-kun";
}
int main() {
cin>>K;
rep(i,K) cin>>iso[i];
rep(i,K) cin>>naka[i];
cout<<solve()<<endl;
return 0;
}
|
488c616c749b26d71fd053b576c297dc31a951bb | cee0a5fa9b69093b9a533e0236be6131dc032877 | /cs371p/quizzes/Quiz20.c++ | ff355fe10211bfbfb1abb4a0a3ceb8651ef8be67 | [] | no_license | ztschir/Object-Oriented-Programming | 7484b98624b560e6008b9f863d87af0512da9a10 | f5048a358af655ba3c194b5f7ebcb12d3037b55f | refs/heads/master | 2021-01-01T17:42:55.743067 | 2013-03-07T04:18:53 | 2013-03-07T04:18:53 | 8,619,875 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 716 | Quiz20.c++ | /*
CS371p: Quiz #20 (5 pts)
*/
/* -----------------------------------------------------------------------
1. Fill in the TWO blanks below:
[The Open-Closed Principle]
(2 pts)
Software entities (classes, modules, functions, etc.) should be open
for <BLANK>, but closed for <BLANK>.
extension
modification
*/
/* -----------------------------------------------------------------------
2. Fill in the TWO blanks below:
[Sec. 11.2, Pg. 224]
(2 pts)
In a statically typed object-oriented programming language, the
legality of a message-passing expression is determined at compile time
based on the <BLANK> class of the receiver and not on its current
<BLANK> value.
static
dynamic
*/
| |
c149732ed73461add61a6fd3a8a18f45a5c63e35 | e0a27d2b4276438d072c4bdfd0127f6364ababc9 | /src/common/dtl/net/jsontextwriter.h | 35aee44b81a210fbd25b5b4f7baa0aa335d0fbb9 | [] | no_license | hanxin1987216/DTL | ab1da2c171a17af382dfcce1523e56ee2d35d3d4 | 2858770cbd645cff0c29911f9518f12a9fb2d5b1 | refs/heads/master | 2021-01-13T14:20:39.364470 | 2013-04-27T03:13:12 | 2013-04-27T03:13:12 | 5,611,146 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,886 | h | jsontextwriter.h | /***************************************************************************************************
jsontextwriter.h:
Copyright (c) Datatom, Inc.(2011 - 2012), All rights reserved.
Purpose:
json text writer
Author:
Lyre
Creating Time:
2012-03-26
***************************************************************************************************/
#ifndef _DTL_NET_JSONTEXTWRITER_H_
#define _DTL_NET_JSONTEXTWRITER_H_
#include <dtprec.h>
#include <stack>
#include "json.h"
enum JsonNodeType
{
JSON_NODE_UNINIT = 0,
JSON_NODE_ARRAY = 1,
JSON_NODE_OBJECT,
};
class DTL_DLLEXPORT JsonPointNode
{
public:
JsonPointNode ()
{
_type = JSON_NODE_UNINIT;
_ptr = NULL;
_label = String::EMPTY;
}
JsonPointNode (const JsonNodeType type, cJSON *ptr, const String &label = String::EMPTY)
{
_type = type;
_ptr = ptr;
_label = label;
}
JsonPointNode (const JsonPointNode &node)
{
_type = node.getType ();
_ptr = node.getPtr ();
_label = node.getLabel ();
}
JsonPointNode& operator =(JsonPointNode& node)
{
this->_type = node.getType ();
this->_ptr = node.getPtr ();
this->_label = node.getLabel ();
return *this;
}
bool operator ==(JsonPointNode& node)
{
return (this->_ptr == node.getPtr ());
}
~JsonPointNode () {}
cJSON* getPtr () const
{
return _ptr;
}
JsonNodeType getType () const
{
return _type;
}
String getLabel () const
{
return _label;
}
private:
JsonNodeType _type;
cJSON* _ptr;
String _label;
};
class DTL_DLLEXPORT JsonTextWriter
{
public:
JsonTextWriter ();
virtual ~JsonTextWriter();
void StartArray (const String &label = String::EMPTY);
void EndArray ();
void StartObject (const String &label = String::EMPTY,cJSON * jsonObject = NULL);
void EndObject ();
void WriteElement (const char *label, const String &value);
void WriteElement (const char *label, const char* value);
void WriteElement (const char *label, const int value);
void WriteElement (const char *label, const unsigned int value);
void WriteElement (const char *label, const int64 value);
void WriteElement (const char *label, const short value);
void WriteElement (const char *label, const unsigned short value);
void WriteElement (const char *label, const bool value);
void WriteNull (const char *label);
public:
String getJsonStr (void);
cJSON* getJsonObject(void);
private:
void WriteString (const char *label, const String &value);
template <class T>
void WriteNumber (const char *label, const T value);
void WriteBool (const char *label, const bool value);
private:
String _jsonStr;
JsonPointNode _root;
JsonPointNode _current;
stack<JsonPointNode> _jsonObjectStack;
bool _hasEnd;
};
#endif // _DTL_NET_JSONTEXTWRITER_H_
|
83324495e12043ca78bfcac1dae290198222f1c1 | f27d5541f832f37a0d8b2ac4f96594cb2e3b4feb | /Duckchess/DuckChess/gamecontroller.h | 8947d0bffdd88cc30f7c5abf5951d821f53623ef | [] | no_license | Daniel-yuan/DuckChess | 91c94db72f74f6b5f7d41ff83ba08a73cc28f35e | ad081ab36a7dac90c1bcde8035406505653014ca | refs/heads/master | 2022-12-11T10:56:35.571316 | 2020-09-13T13:02:33 | 2020-09-13T13:02:33 | 295,150,470 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,527 | h | gamecontroller.h | #ifndef GAMECONTROLLER_H
#define GAMECONTROLLER_H
#include <QObject>
#include <QTimer>
class QGraphicsScene;
class QTimer;
class QGraphicsSceneMouseEvent;
class ChessBoard;
class Chess;
class ReachablePlace;
struct Moves {
int x1, y1, chess1;
int x2, y2, chess2;
Moves *Pre;
Moves () { Pre = nullptr; }
};
class GameController : public QObject
{
Q_OBJECT
public:
GameController(QGraphicsScene &scene, QWidget *parent = nullptr);
~GameController();
public slots:
void pause();
void resume();
void GiveUp();
void RegretChess();
protected:
bool eventFilter(QObject *object, QEvent *event);
private:
void Init();
void ScreenPrint();
void ScreenInit();
void MousePressed(QGraphicsSceneMouseEvent *event);
bool Canmove(int x, int y, int nx, int ny, int Camp);
bool Capt(int x, int y, int nx, int ny);
bool Guar(int x, int y, int nx, int ny);
bool Elep(int x, int y, int nx, int ny);
bool Hors(int x, int y, int nx, int ny);
bool Cars(int x, int y, int nx, int ny);
bool Duck(int x, int y, int nx, int ny);
bool Sold(int x, int y, int nx, int ny);
void GameOver();
void GameStart();
QGraphicsScene &scene;
QTimer timer;
bool Pressed;
int Nowperson;
int Board[15][15];
int Reach[15][15];
int Readyx, Readyy;
QWidget *PARENT;
bool ShouldRefresh;
Chess *chess[15][15];
ReachablePlace *place[15][15];
ChessBoard *chessboard;
Moves *CurrentTop;
};
#endif // GAMECONTROLLER_H
|
281b7a02f83e3c929309026c7bed17252128ff6a | a5f3b0001cdb692aeffc444a16f79a0c4422b9d0 | /main/basic/source/comp/io.cxx | 66a63301611737041a46d198a3b7b46894ce2df6 | [
"Apache-2.0",
"CPL-1.0",
"bzip2-1.0.6",
"LicenseRef-scancode-other-permissive",
"Zlib",
"LZMA-exception",
"LGPL-2.0-or-later",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-philippe-de-muyter",
"OFL-1.1",
"LGPL-2.1-only",
"MPL-1.1",
"X11",
"LGPL-2.1-or-later",
"GPL-2.0-only",
... | permissive | apache/openoffice | b9518e36d784898c6c2ea3ebd44458a5e47825bb | 681286523c50f34f13f05f7b87ce0c70e28295de | refs/heads/trunk | 2023-08-30T15:25:48.357535 | 2023-08-28T19:50:26 | 2023-08-28T19:50:26 | 14,357,669 | 907 | 379 | Apache-2.0 | 2023-08-16T20:49:37 | 2013-11-13T08:00:13 | C++ | UTF-8 | C++ | false | false | 7,511 | cxx | io.cxx | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"
#include <tools/stream.hxx>
#include "sbcomp.hxx"
#include "iosys.hxx"
// Test, ob ein I/O-Channel angegeben wurde
sal_Bool SbiParser::Channel( sal_Bool bAlways )
{
sal_Bool bRes = sal_False;
Peek();
if( IsHash() )
{
SbiExpression aExpr( this );
while( Peek() == COMMA || Peek() == SEMICOLON )
Next();
aExpr.Gen();
aGen.Gen( _CHANNEL );
bRes = sal_True;
}
else if( bAlways )
Error( SbERR_EXPECTED, "#" );
return bRes;
}
// Fuer PRINT und WRITE wird bei Objektvariablen versucht,
// die Default-Property anzusprechen.
// PRINT
void SbiParser::Print()
{
sal_Bool bChan = Channel();
// Die Ausdruecke zum Drucken:
while( !bAbort )
{
if( !IsEoln( Peek() ) )
{
SbiExpression* pExpr = new SbiExpression( this );
pExpr->Gen();
delete pExpr;
Peek();
aGen.Gen( eCurTok == COMMA ? _PRINTF : _BPRINT );
}
if( eCurTok == COMMA || eCurTok == SEMICOLON )
{
Next();
if( IsEoln( Peek() ) ) break;
}
else
{
aGen.Gen( _PRCHAR, '\n' );
break;
}
}
if( bChan )
aGen.Gen( _CHAN0 );
}
// WRITE #chan, expr, ...
void SbiParser::Write()
{
sal_Bool bChan = Channel();
// Die Ausdruecke zum Drucken:
while( !bAbort )
{
SbiExpression* pExpr = new SbiExpression( this );
pExpr->Gen();
delete pExpr;
aGen.Gen( _BWRITE );
if( Peek() == COMMA )
{
aGen.Gen( _PRCHAR, ',' );
Next();
if( IsEoln( Peek() ) ) break;
}
else
{
aGen.Gen( _PRCHAR, '\n' );
break;
}
}
if( bChan )
aGen.Gen( _CHAN0 );
}
// #i92642 Handle LINE keyword outside ::Next()
void SbiParser::Line()
{
// #i92642: Special handling to allow name as symbol
if( Peek() == INPUT )
{
Next();
LineInput();
}
else
{
aGen.Statement();
KeywordSymbolInfo aInfo;
aInfo.m_aKeywordSymbol = String( RTL_CONSTASCII_USTRINGPARAM( "line" ) );
aInfo.m_eSbxDataType = GetType();
aInfo.m_eTok = SYMBOL;
Symbol( &aInfo );
}
}
// LINE INPUT [prompt], var$
void SbiParser::LineInput()
{
Channel( sal_True );
// sal_Bool bChan = Channel( sal_True );
SbiExpression* pExpr = new SbiExpression( this, SbOPERAND );
/* AB 15.1.96: Keinen allgemeinen Ausdruck mehr zulassen
SbiExpression* pExpr = new SbiExpression( this );
if( !pExpr->IsVariable() )
{
SbiToken eTok = Peek();
if( eTok == COMMA || eTok == SEMICOLON ) Next();
else Error( SbERR_EXPECTED, COMMA );
// mit Prompt
if( !bChan )
{
pExpr->Gen();
aGen.Gen( _PROMPT );
}
else
Error( SbERR_VAR_EXPECTED );
delete pExpr;
pExpr = new SbiExpression( this, SbOPERAND );
}
*/
if( !pExpr->IsVariable() )
Error( SbERR_VAR_EXPECTED );
if( pExpr->GetType() != SbxVARIANT && pExpr->GetType() != SbxSTRING )
Error( SbERR_CONVERSION );
pExpr->Gen();
aGen.Gen( _LINPUT );
delete pExpr;
aGen.Gen( _CHAN0 ); // ResetChannel() nicht mehr in StepLINPUT()
}
// INPUT
void SbiParser::Input()
{
aGen.Gen( _RESTART );
Channel( sal_True );
// sal_Bool bChan = Channel( sal_True );
SbiExpression* pExpr = new SbiExpression( this, SbOPERAND );
/* ALT: Jetzt keinen allgemeinen Ausdruck mehr zulassen
SbiExpression* pExpr = new SbiExpression( this );
...
siehe LineInput
*/
while( !bAbort )
{
if( !pExpr->IsVariable() )
Error( SbERR_VAR_EXPECTED );
pExpr->Gen();
aGen.Gen( _INPUT );
if( Peek() == COMMA )
{
Next();
delete pExpr;
pExpr = new SbiExpression( this, SbOPERAND );
}
else break;
}
delete pExpr;
aGen.Gen( _CHAN0 ); // ResetChannel() nicht mehr in StepINPUT()
}
// OPEN stringexpr FOR mode ACCCESS access mode AS Channel [Len=n]
void SbiParser::Open()
{
SbiExpression aFileName( this );
SbiToken eTok;
TestToken( FOR );
short nMode = 0;
short nFlags = 0;
switch( Next() )
{
case INPUT:
nMode = STREAM_READ; nFlags |= SBSTRM_INPUT; break;
case OUTPUT:
nMode = STREAM_WRITE | STREAM_TRUNC; nFlags |= SBSTRM_OUTPUT; break;
case APPEND:
nMode = STREAM_WRITE; nFlags |= SBSTRM_APPEND; break;
case RANDOM:
nMode = STREAM_READ | STREAM_WRITE; nFlags |= SBSTRM_RANDOM; break;
case BINARY:
nMode = STREAM_READ | STREAM_WRITE; nFlags |= SBSTRM_BINARY; break;
default:
Error( SbERR_SYNTAX );
}
if( Peek() == ACCESS )
{
Next();
eTok = Next();
// #27964# Nur STREAM_READ,STREAM_WRITE-Flags in nMode beeinflussen
nMode &= ~(STREAM_READ | STREAM_WRITE); // loeschen
if( eTok == READ )
{
if( Peek() == WRITE )
{
Next();
nMode |= (STREAM_READ | STREAM_WRITE);
}
else
nMode |= STREAM_READ;
}
else if( eTok == WRITE )
nMode |= STREAM_WRITE;
else
Error( SbERR_SYNTAX );
}
switch( Peek() )
{
#ifdef SHARED
#undef SHARED
#define tmpSHARED
#endif
case SHARED:
Next(); nMode |= STREAM_SHARE_DENYNONE; break;
#ifdef tmpSHARED
#define SHARED
#undef tmpSHARED
#endif
case LOCK:
Next();
eTok = Next();
if( eTok == READ )
{
if( Peek() == WRITE ) Next(), nMode |= STREAM_SHARE_DENYALL;
else nMode |= STREAM_SHARE_DENYREAD;
}
else if( eTok == WRITE )
nMode |= STREAM_SHARE_DENYWRITE;
else
Error( SbERR_SYNTAX );
break;
default: break;
}
TestToken( AS );
// Die Kanalnummer
SbiExpression* pChan = new SbiExpression( this );
if( !pChan )
Error( SbERR_SYNTAX );
SbiExpression* pLen = NULL;
if( Peek() == SYMBOL )
{
Next();
String aLen( aSym );
if( aLen.EqualsIgnoreCaseAscii( "LEN" ) )
{
TestToken( EQ );
pLen = new SbiExpression( this );
}
}
if( !pLen ) pLen = new SbiExpression( this, 128, SbxINTEGER );
// Der Stack fuer den OPEN-Befehl sieht wie folgt aus:
// Blocklaenge
// Kanalnummer
// Dateiname
pLen->Gen();
if( pChan )
pChan->Gen();
aFileName.Gen();
aGen.Gen( _OPEN, nMode, nFlags );
delete pLen;
delete pChan;
}
// NAME file AS file
void SbiParser::Name()
{
// #i92642: Special handling to allow name as symbol
if( Peek() == EQ )
{
aGen.Statement();
KeywordSymbolInfo aInfo;
aInfo.m_aKeywordSymbol = String( RTL_CONSTASCII_USTRINGPARAM( "name" ) );
aInfo.m_eSbxDataType = GetType();
aInfo.m_eTok = SYMBOL;
Symbol( &aInfo );
return;
}
SbiExpression aExpr1( this );
TestToken( AS );
SbiExpression aExpr2( this );
aExpr1.Gen();
aExpr2.Gen();
aGen.Gen( _RENAME );
}
// CLOSE [n,...]
void SbiParser::Close()
{
Peek();
if( IsEoln( eCurTok ) )
aGen.Gen( _CLOSE, 0 );
else
for( ;; )
{
SbiExpression aExpr( this );
while( Peek() == COMMA || Peek() == SEMICOLON )
Next();
aExpr.Gen();
aGen.Gen( _CHANNEL );
aGen.Gen( _CLOSE, 1 );
if( IsEoln( Peek() ) )
break;
}
}
|
86495885f78d7288ad96ee1cc35f9044206e9955 | 5978cc964c71a3de2451207b58743111d133b872 | /Test.cpp | bde4b6767de04604bd134a2e622c09ccf92c5c4a | [] | no_license | darsam44/phonetic-search-a- | e5e4afed3e47007167acc8bbaf63387f28cac7af | 8a40cdfccaa61e9bc09b8dda0ecac690124fe9eb | refs/heads/master | 2021-04-08T04:48:31.007137 | 2020-07-25T18:02:20 | 2020-07-25T18:02:20 | 248,741,682 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 7,585 | cpp | Test.cpp | #include "PhoneticFinder.hpp"
#include "doctest.h"
#include <iostream>
#include <stdexcept>
using namespace std;
TEST_CASE("v and w")
{
string text = "who did this i want to verify this";
CHECK( phonetic::find(text,"who").compare("who") == 0 );
CHECK( phonetic::find(text,"Vho").compare("who") == 0 );
CHECK( phonetic::find(text,"Who").compare("who") == 0 );
CHECK( phonetic::find(text,"who").compare("who") == 0 );
CHECK( phonetic::find(text,"want").compare("want") == 0 );
CHECK( phonetic::find(text,"Want").compare("want") == 0 );
CHECK( phonetic::find(text,"Vant").compare("want") == 0 );
CHECK( phonetic::find(text,"vant").compare("want") == 0 );
CHECK( phonetic::find(text,"Verify").compare("verify") == 0 );
CHECK( phonetic::find(text,"verify").compare("verify") == 0 );
CHECK( phonetic::find(text,"Werify").compare("verify") == 0 );
CHECK( phonetic::find(text,"werify").compare("verify") == 0 );
}
TEST_CASE("b and f and p")
{
string text = "people cant fuy flowers on friday because the store is close";
CHECK( phonetic::find(text,"buy").compare("fuy") == 0 );
CHECK( phonetic::find(text,"Peoble").compare("people") == 0 );
CHECK( phonetic::find(text,"Beofle").compare("people") == 0 );
CHECK( phonetic::find(text,"feoBle").compare("people") == 0 );
CHECK( phonetic::find(text,"FeoPle").compare("people") == 0 );
CHECK( phonetic::find(text,"PeoPle").compare("people") == 0 );
CHECK( phonetic::find(text,"BeoPle").compare("people") == 0 );
//
CHECK( phonetic::find(text,"Flowers").compare("flowers") == 0 );
CHECK( phonetic::find(text,"Plowers").compare("flowers") == 0 );
CHECK( phonetic::find(text,"plowers").compare("flowers") == 0 );
CHECK( phonetic::find(text,"Blowers").compare("flowers") == 0 );
CHECK( phonetic::find(text,"blowers").compare("flowers") == 0 );
CHECK( phonetic::find(text,"flowers").compare("flowers") == 0 );
//
CHECK( phonetic::find(text,"because").compare("because") == 0 );
CHECK( phonetic::find(text,"Because").compare("because") == 0 );
CHECK( phonetic::find(text,"Fecause").compare("because") == 0 );
CHECK( phonetic::find(text,"fecause").compare("because") == 0 );
CHECK( phonetic::find(text,"pecause").compare("because") == 0 );
CHECK( phonetic::find(text,"Pecause").compare("because") == 0 );
//
CHECK( phonetic::find(text,"friday").compare("friday") == 0 );
CHECK( phonetic::find(text,"Friday").compare("friday") == 0 );
CHECK( phonetic::find(text,"Priday").compare("friday") == 0 );
CHECK( phonetic::find(text,"priday").compare("friday") == 0 );
CHECK( phonetic::find(text,"briday").compare("friday") == 0 );
CHECK( phonetic::find(text,"Briday").compare("friday") == 0 );
}
TEST_CASE("g and j")
{
string text = "gal jump on the grass ";
CHECK( phonetic::find(text,"gal").compare("gal") == 0 );
CHECK( phonetic::find(text,"jal").compare("gal") == 0 );
CHECK( phonetic::find(text,"Gal").compare("gal") == 0 );
CHECK( phonetic::find(text,"Jal").compare("gal") == 0 );
//
CHECK( phonetic::find(text,"jump").compare("jump") == 0 );
CHECK( phonetic::find(text,"Jump").compare("jump") == 0 );
CHECK( phonetic::find(text,"gump").compare("jump") == 0 );
CHECK( phonetic::find(text,"Gump").compare("jump") == 0 );
//
CHECK( phonetic::find(text,"grass").compare("grass") == 0 );
CHECK( phonetic::find(text,"Grass").compare("grass") == 0 );
CHECK( phonetic::find(text,"Jrass").compare("grass") == 0 );
CHECK( phonetic::find(text,"jrass").compare("grass") == 0 );
}
TEST_CASE("c and k and q")
{
string text = "The cats eat the cakes quickly";
CHECK( phonetic::find(text,"cats").compare("cats") == 0 );
CHECK( phonetic::find(text,"Cats").compare("cats") == 0 );
CHECK( phonetic::find(text,"kats").compare("cats") == 0 );
CHECK( phonetic::find(text,"Kats").compare("cats") == 0 );
CHECK( phonetic::find(text,"qats").compare("cats") == 0 );
CHECK( phonetic::find(text,"Qats").compare("cats") == 0 );
//
CHECK( phonetic::find(text,"cakes").compare("cakes") == 0 );
CHECK( phonetic::find(text,"CaQes").compare("cakes") == 0 );
CHECK( phonetic::find(text,"Kaqes").compare("cakes") == 0 );
CHECK( phonetic::find(text,"kaces").compare("cakes") == 0 );
CHECK( phonetic::find(text,"qaCes").compare("cakes") == 0 );
CHECK( phonetic::find(text,"Qakes").compare("cakes") == 0 );
//
CHECK( phonetic::find(text,"quickly").compare("quickly") == 0 );
CHECK( phonetic::find(text,"KuicCly").compare("quickly") == 0 );
CHECK( phonetic::find(text,"quicCly").compare("quickly") == 0 );
CHECK( phonetic::find(text,"Cuicqly").compare("quickly") == 0 );
}
TEST_CASE("z and s")
{
string text = "lets go to the zoo";
CHECK( phonetic::find(text,"lets").compare("lets") == 0 );
CHECK( phonetic::find(text,"letS").compare("lets") == 0 );
CHECK( phonetic::find(text,"letz").compare("lets") == 0 );
CHECK( phonetic::find(text,"letZ").compare("lets") == 0 );
//
CHECK( phonetic::find(text,"zoo").compare("zoo") == 0 );
CHECK( phonetic::find(text,"soo").compare("zoo") == 0 );
CHECK( phonetic::find(text,"Soo").compare("zoo") == 0 );
}
TEST_CASE("d and t")
{
string text = "lets go to the doctor";
CHECK( phonetic::find(text,"leds").compare("lets") == 0 );
CHECK( phonetic::find(text,"letS").compare("lets") == 0 );
CHECK( phonetic::find(text,"leDz").compare("lets") == 0 );
CHECK( phonetic::find(text,"ledZ").compare("lets") == 0 );
//
CHECK( phonetic::find(text,"toctor").compare("doctor") == 0 );
CHECK( phonetic::find(text,"Toctor").compare("doctor") == 0 );
CHECK( phonetic::find(text,"Doctor").compare("doctor") == 0 );
}
TEST_CASE("o and u")
{
string text = "lets go to the jerusalem";
CHECK( phonetic::find(text,"jerusalem").compare("jerusalem") == 0 );
CHECK( phonetic::find(text,"jerosalem").compare("jerusalem") == 0 );
CHECK( phonetic::find(text,"jerOsalem").compare("jerusalem") == 0 );
CHECK( phonetic::find(text,"jerUsalem").compare("jerusalem") == 0 );
//
CHECK( phonetic::find(text,"gu").compare("go") == 0 );
CHECK( phonetic::find(text,"gU").compare("go") == 0 );
CHECK( phonetic::find(text,"gO").compare("go") == 0 );
}
TEST_CASE("i and y")
{
string text = "yesterday i bought ice-cream";
CHECK( phonetic::find(text,"Yce-cream").compare("ice-cream") == 0 );
CHECK( phonetic::find(text,"yce-cream").compare("ice-cream") == 0 );
CHECK( phonetic::find(text,"Ice-cream").compare("ice-cream") == 0 );
//
CHECK( phonetic::find(text,"Y").compare("i") == 0 );
CHECK( phonetic::find(text,"I").compare("i") == 0 );
//
CHECK( phonetic::find(text,"Yesterdai").compare("yesterday") == 0 );
CHECK( phonetic::find(text,"iesterdaI").compare("yesterday") == 0 );
CHECK( phonetic::find(text,"IesterdaY").compare("yesterday") == 0 );
CHECK( phonetic::find(text,"Yesterday").compare("yesterday") == 0 );
}
TEST_CASE("all")
{
string text = "I dont like coron virus ";
CHECK( phonetic::find(text,"vyruZ").compare("virus") == 0 );
CHECK( phonetic::find(text,"wYrOz").compare("virus") == 0 );
CHECK( phonetic::find(text,"WirOs").compare("virus") == 0 );
CHECK( phonetic::find(text,"WirOZ").compare("virus") == 0 );
CHECK( phonetic::find(text,"virus").compare("virus") == 0 );
//
CHECK( phonetic::find(text,"KUrun").compare("coron") == 0 );
CHECK( phonetic::find(text,"kurOn").compare("coron") == 0 );
CHECK( phonetic::find(text,"QUron").compare("coron") == 0 );
//
CHECK( phonetic::find(text,"lYCe").compare("like") == 0 );
CHECK( phonetic::find(text,"lIce").compare("like") == 0 );
CHECK( phonetic::find(text,"lyQe").compare("like") == 0 );
CHECK( phonetic::find(text,"lYqe").compare("like") == 0 );
} |
70b3ae8627a48c03574855f1d4d8dba00a92db65 | be497f1447309f51e3bfe7a33515c76ea5e093f9 | /src/checkpoint/cp_mgr.h | f816ed10a755c33ceb8cae7068c5977440880ec7 | [
"BSD-3-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"LicenseRef-scancode-unknown-license-reference",
"OpenSSL",
"BSD-2-Clause"
] | permissive | rjzou/phxpaxos | f537d9b556a3a65efd60d62eaaf6cc59f618fa9c | c9bfe39e3557f244def6ba5974da2f37e1a42032 | refs/heads/master | 2022-04-13T16:24:13.685964 | 2020-04-10T15:20:48 | 2020-04-10T15:20:48 | 254,642,632 | 1 | 0 | NOASSERTION | 2020-04-10T13:34:14 | 2020-04-10T13:34:13 | null | UTF-8 | C++ | false | false | 2,139 | h | cp_mgr.h | /*
Tencent is pleased to support the open source community by making
PhxPaxos available.
Copyright (C) 2016 THL A29 Limited, a Tencent company.
All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
https://opensource.org/licenses/BSD-3-Clause
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.
See the AUTHORS file for names of contributors.
*/
#pragma once
#include "replayer.h"
#include "cleaner.h"
#include "phxpaxos/options.h"
#include <set>
namespace phxpaxos
{
class CheckpointMgr
{
public:
CheckpointMgr(
Config * poConfig,
SMFac * poSMFac,
LogStorage * poLogStorage,
const bool bUseCheckpointReplayer);
~CheckpointMgr();
int Init();
void Start();
void Stop();
Replayer * GetReplayer();
Cleaner * GetCleaner();
public:
int PrepareForAskforCheckpoint(const nodeid_t iSendNodeID);
const bool InAskforcheckpointMode() const;
void ExitCheckpointMode();
public:
const uint64_t GetMinChosenInstanceID() const;
int SetMinChosenInstanceID(const uint64_t llMinChosenInstanceID);
void SetMinChosenInstanceIDCache(const uint64_t llMinChosenInstanceID);
const uint64_t GetCheckpointInstanceID() const;
const uint64_t GetMaxChosenInstanceID() const;
void SetMaxChosenInstanceID(const uint64_t llMaxChosenInstanceID);
private:
Config * m_poConfig;
LogStorage * m_poLogStorage;
SMFac * m_poSMFac;
Replayer m_oReplayer;
Cleaner m_oCleaner;
uint64_t m_llMinChosenInstanceID;
uint64_t m_llMaxChosenInstanceID;
private:
bool m_bInAskforCheckpointMode;
std::set<nodeid_t> m_setNeedAsk;
uint64_t m_llLastAskforCheckpointTime;
bool m_bUseCheckpointReplayer;
};
}
|
ce3430cedea5e842e1fa7f759598d5e94239b4c1 | 6fde2629fddfcd117daa44428228efefb67dd275 | /c/file/file03/file03.cpp | cfb514caccfe719be6b3c9d41a3764008869ac1b | [] | no_license | i131313/visual-stdio_C | 78fcda401b9bd75d9ab40831b09e1aa8ddcb2c81 | 7b1c62d2d5ea0a5bb263df4ba747cb87e6a4e0b3 | refs/heads/master | 2021-01-09T20:41:35.697240 | 2016-07-17T06:26:18 | 2016-07-17T06:26:18 | 63,517,736 | 0 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 285 | cpp | file03.cpp | #include<stdio.h>
int main(void)
{
FILE *fp;
int a[3];
fp = fopen("mybinary.b","rb");
if(fp == NULL)
{
perror("ファイルがオープンできません\n");
return -1;
}
fread(a, sizeof(int), 3, fp);
fclose(fp);
printf("%d, %d, %d\n",a[0], a[1], a[2]);
return 0;
} |
841c78ab22757d3a7b56dc605f74a615cb6fb546 | c0108fc083560935b02235c184ec5b80af508fc8 | /include/ros_marty/cmd_server.hpp | 971768b1f9b2e3197ebe89f7886c2ab81717d9ba | [
"Apache-2.0"
] | permissive | robotical/ros_marty | a00e0f7f5454b86fd1f133b83bbfdd00ee7a585f | 739aef38f7dd43927a1e3209b1d3521624d84bc4 | refs/heads/master | 2021-07-13T17:46:10.876893 | 2017-08-25T14:23:02 | 2017-08-25T14:23:02 | 72,796,545 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,219 | hpp | cmd_server.hpp | /**
* @file cmd_server.hpp
* @brief CMD Server for Marty, enabling execution of CMDs remotely
* @author Alejandro Bordallo <alex.bordallo@robotical.io>
* @date 2016-02-06
* @copyright (Apache) 2016 Robotical Ltd.
*/
#ifndef CMD_SERVER_HPP
#define CMD_SERVER_HPP
// System
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <signal.h>
// Marty
#include "marty_msgs/Command.h"
#include "marty_msgs/ServoMsg.h"
#include "marty_msgs/ServoMsgArray.h"
#include "ros_marty/marty_core.hpp"
#include "ros_marty/trajectory.hpp"
// ROS
#include "std_msgs/Float32.h"
#include "geometry_msgs/Pose2D.h"
#include "marty_msgs/GPIOs.h"
#include "marty_msgs/Accelerometer.h"
#include "marty_msgs/MotorCurrents.h"
// #define PORT 1569
#define PORT 1569
// This wait time is required when a stop message is sent straight after
#define stop_wait 150 // Wait time between instantaneous servo commands
/**
* @brief Add new commands here for the server to receive
*/
enum Direction {
CMD_LEFT = 0,
CMD_RIGHT,
CMD_FORW,
CMD_BACK
};
enum Axis {
AXES_X = 0,
AXES_Y,
AXES_Z
};
enum Joint {
J_HIP = 0,
J_TWIST,
J_KNEE,
J_LEG,
J_ARM,
J_EYES
};
enum Commands {
CMD_HELLO = 0,
CMD_MOVEJOINT,
CMD_LEAN,
CMD_WALK,
CMD_EYES,
CMD_KICK,
CMD_LIFTLEG,
CMD_LOWERLEG,
CMD_CELEBRATE,
CMD_DANCE,
CMD_ROLLERSKATE,
CMD_ARMS,
CMD_DEMO,
CMD_GET,
CMD_SIDESTEP,
CMD_STRAIGHT,
CMD_SOUND,
CMD_STOP
};
enum Sensors {
GET_GPIO = 0,
GET_ACCEL,
GET_BATT,
GET_CURR,
GET_BALL
};
class CmdServer {
protected:
ros::NodeHandle nh_;
void loadParams();
void init();
void rosSetup();
private:
// Methods
void runCommand(vector<int> data);
void runSockCommand(vector<int8_t> data);
void arms(int r_angle = 0, int l_angle = 0);
void celebrate(int move_time = 4000);
void dance(int robot_id);
void demo();
void eyes(int amount = 0, int amount2 = 0);
void getData(int sensor, int id);
void hello();
void kick(int side = CMD_LEFT, int move_time = 3000);
void lean(int dir, int amount = 100, int move_time = 2000);
void liftLeg(int leg, int amount = 100, int move_time = 2000);
void lowerLeg(int move_time = 1000);
void moveJoint(int side, int joint, int amount, int move_time = 2000);
void sideStep(int side, int num_steps = 1, int move_time = 1000,
int step_length = 50);
void standStraight(int move_time = 1000);
void playSound(int freq = 440, int duration = 500);
void playSounds(std::vector<int> sounds);
void stopRobot();
void walk(int num_steps = 2, int turn = 0,
int move_time = 3000, int step_length = 50, int side = -1);
void testLeg(int side, int duration);
void sitBack(int duration);
void swingArms(int r_arm, int l_arm, int duration = 2000, int cycles = 4);
void swingJoints(marty_msgs::ServoMsgArray, int duration = 2000,
int cycles = 4);
void gpioCB(const marty_msgs::GPIOs& msg) {gpio_data_ = msg;}
void accelCB(const marty_msgs::Accelerometer& msg) {accel_data_ = msg;}
void battCB(const std_msgs::Float32& msg) {batt_data_ = msg;}
void currCB(const marty_msgs::MotorCurrents& msg) {curr_data_ = msg;}
void ballCB(const geometry_msgs::Pose2D& msg) {ball_pos_ = msg;}
bool cmd_service(marty_msgs::Command::Request& req,
marty_msgs::Command::Response& res);
// Flags
bool busy_;
bool ros_cmd_;
bool resp_request_;
bool turn_spot_;
// Params
bool ready_move_;
// Variables
MartyCore* robot_;
int sock_;
float interp_dt_;
std::vector<int> cmd_data_;
std::vector<std::vector<int> > cmd_queue_;
float val_request_;
marty_msgs::GPIOs gpio_data_;
marty_msgs::Accelerometer accel_data_;
std_msgs::Float32 batt_data_;
marty_msgs::MotorCurrents curr_data_;
geometry_msgs::Pose2D ball_pos_;
// ROS
ros::Subscriber gpio_sub_;
ros::Subscriber accel_sub_;
ros::Subscriber batt_sub_;
ros::Subscriber curr_sub_;
ros::Subscriber ball_sub_;
ros::ServiceServer cmd_srv_;
public:
CmdServer(ros::NodeHandle& nh);
~CmdServer();
void robotReady();
void setupServer();
void stopServer();
void waitForCmd();
};
#endif /* CMD_SERVER_HPP */
|
b982806ee77b2de4541413acac2d85f15cc4ba59 | d42607e659397dbb8c94980e3b18537867763521 | /include/viewController/StackViewController.h | 3c052cc36d612a27338a77fc9fc347cfa271dccc | [] | no_license | igorJarek/SourceStructAnalyzer | 300339d93db8e644e66bc80f290f05ad389675a7 | 29ed80a4297b2b8bbb674a785e10d5be930aeec9 | refs/heads/master | 2020-08-29T19:45:30.548331 | 2020-01-10T01:10:51 | 2020-01-10T01:10:51 | 218,152,621 | 1 | 0 | null | 2019-12-29T13:19:26 | 2019-10-28T21:55:53 | C++ | UTF-8 | C++ | false | false | 1,333 | h | StackViewController.h | #ifndef STACKVIEWCONTROLLER_H
#define STACKVIEWCONTROLLER_H
#include <viewController/ViewController.h>
#include <windows.h>
#include <TextExt.h>
#include <Resource.h>
class StackViewController : public ViewController
{
public:
StackViewController(VideoMode& mode, const string& title, Uint32 style = Style::Default);
~StackViewController();
virtual void close(const Event& event);
virtual void resize(const Event& event);
virtual void leftButtonPressed(const Event& event);
virtual void midleButtonPressed(const Event& event);
virtual void rightButtonPressed(const Event& event);
virtual void leftButtonReleased(const Event& event);
virtual void midleButtonReleased(const Event& event);
virtual void rightButtonReleased(const Event& event);
virtual void mouseWheel(const Event& event);
virtual void mouseMove(const Event& event);
virtual void keyboardPressed(const Event& event);
virtual void keyboardReleased(const Event& event);
virtual void draw();
void addTextData(const string& functionBlockName, size_t functionStagePosition, const string& clickedFunction, size_t clickedFunctionStagePosition);
private:
vector<TextExt> m_textExtVector;
};
#endif // STACKVIEWCONTROLLER_H
|
6e1b1f2fee283ef91e2d0b9e03a9a1612c75fc88 | 5caa022343a8280437c7a39afd1752f3c5325086 | /C++/92.LOSTMAX.cpp | a18fb830871b88f9ed3abfb57470a2a3d700b838 | [] | no_license | DS-73/CodeChef | d817b7182d6a9b6608996d88d40997ccfddc27fb | 4d45c6f92ee3836be2cac3fd5a2e0ec49249a61d | refs/heads/master | 2023-02-07T10:54:03.718742 | 2020-12-30T17:32:54 | 2020-12-30T17:32:54 | 294,760,796 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | cpp | 92.LOSTMAX.cpp | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
int t;
cin >> t;
getchar();
while(t--){
string s;
getline(cin, s);
int flag = 0;
vector<int64_t> v;
for(int i = 0; s[i] != NULL; i++){
if(s[i] == ' '){
flag = 0;
}
else{
if(flag == 0){
v.push_back(s[i] - 48);
}
else{
v[v.size() - 1] = (v[v.size() - 1] * 10) + (s[i] - 48);
}
flag = 1;
}
}
flag = 0;
int64_t max = -1;
for(int i = 0; i < v.size(); i++){
if((flag == 0) && (v[i] == v.size() - 1)){
flag = 1;
continue;
}
else if(max < v[i]){
max = v[i];
}
}
cout << max << endl;
}
return 0;
}
|
89a1cd5dac33ef7ff0ff42aae17e4cd062bf4688 | 819529ec3d279936d35b17f6aa91b0c61f23f4c6 | /wecode/BaiTapConTro/bai tap 9.cpp | 0d7dae5c961e5824489a98d750c3eef59322c80b | [] | no_license | dvphuonguyen/IT001.K16 | 0929a7706181c5183b09f65a63887af8d63b855f | fbc66ca8d71ca0dc37ebf9683f8bf07edeb2b536 | refs/heads/main | 2023-08-21T19:32:37.701718 | 2021-10-08T07:20:10 | 2021-10-08T07:20:10 | 414,839,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | cpp | bai tap 9.cpp | #include <iostream>
using namespace std;
void f1(int *t)
{
*t=99;
}
int main()
{
int *p1,*p2;
p1= new int ;
*p1 = 50;
p2=p1;
//p2=p1=50
f1(p2);
//p2=99=p1
cout<<*p1<<" "<<*p2<<endl;
//99 99
p1=new int ;
*p1=88;
cout<<*p1<<" "<<*p2<<endl;
//88 99
delete p1;
delete p2;
}
|
3de2cab83d2667c93f0c8b07156a963654ff3bd1 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/new_hunk_5973.cpp | b88a27317f10f98dd1262bd3579339ca367af76d | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,736 | cpp | new_hunk_5973.cpp | free(filename);
return NULL;
}
/* Helpers for fetching objects (loose) */
static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
void *data)
{
unsigned char expn[4096];
size_t size = eltsize * nmemb;
int posn = 0;
struct http_object_request *freq =
(struct http_object_request *)data;
do {
ssize_t retval = xwrite(freq->localfile,
(char *) ptr + posn, size - posn);
if (retval < 0)
return posn;
posn += retval;
} while (posn < size);
freq->stream.avail_in = size;
freq->stream.next_in = ptr;
do {
freq->stream.next_out = expn;
freq->stream.avail_out = sizeof(expn);
freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
git_SHA1_Update(&freq->c, expn,
sizeof(expn) - freq->stream.avail_out);
} while (freq->stream.avail_in && freq->zret == Z_OK);
data_received++;
return size;
}
struct http_object_request *new_http_object_request(const char *base_url,
unsigned char *sha1)
{
char *hex = sha1_to_hex(sha1);
char *filename;
char prevfile[PATH_MAX];
char *url;
int prevlocal;
unsigned char prev_buf[PREV_BUF_SIZE];
ssize_t prev_read = 0;
long prev_posn = 0;
char range[RANGE_HEADER_SIZE];
struct curl_slist *range_header = NULL;
struct http_object_request *freq;
freq = xmalloc(sizeof(*freq));
hashcpy(freq->sha1, sha1);
freq->localfile = -1;
filename = sha1_file_name(sha1);
snprintf(freq->filename, sizeof(freq->filename), "%s", filename);
snprintf(freq->tmpfile, sizeof(freq->tmpfile),
"%s.temp", filename);
snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
unlink_or_warn(prevfile);
rename(freq->tmpfile, prevfile);
unlink_or_warn(freq->tmpfile);
if (freq->localfile != -1)
error("fd leakage in start: %d", freq->localfile);
freq->localfile = open(freq->tmpfile,
O_WRONLY | O_CREAT | O_EXCL, 0666);
/*
* This could have failed due to the "lazy directory creation";
* try to mkdir the last path component.
*/
if (freq->localfile < 0 && errno == ENOENT) {
char *dir = strrchr(freq->tmpfile, '/');
if (dir) {
*dir = 0;
mkdir(freq->tmpfile, 0777);
*dir = '/';
}
freq->localfile = open(freq->tmpfile,
O_WRONLY | O_CREAT | O_EXCL, 0666);
}
if (freq->localfile < 0) {
error("Couldn't create temporary file %s for %s: %s",
freq->tmpfile, freq->filename, strerror(errno));
goto abort;
}
memset(&freq->stream, 0, sizeof(freq->stream));
git_inflate_init(&freq->stream);
git_SHA1_Init(&freq->c);
url = get_remote_object_url(base_url, hex, 0);
freq->url = xstrdup(url);
/*
* If a previous temp file is present, process what was already
* fetched.
*/
prevlocal = open(prevfile, O_RDONLY);
if (prevlocal != -1) {
do {
prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
if (prev_read>0) {
if (fwrite_sha1_file(prev_buf,
1,
prev_read,
freq) == prev_read) {
prev_posn += prev_read;
} else {
prev_read = -1;
}
}
} while (prev_read > 0);
close(prevlocal);
}
unlink_or_warn(prevfile);
/*
* Reset inflate/SHA1 if there was an error reading the previous temp
* file; also rewind to the beginning of the local file.
*/
if (prev_read == -1) {
memset(&freq->stream, 0, sizeof(freq->stream));
git_inflate_init(&freq->stream);
git_SHA1_Init(&freq->c);
if (prev_posn>0) {
prev_posn = 0;
lseek(freq->localfile, 0, SEEK_SET);
ftruncate(freq->localfile, 0);
}
}
freq->slot = get_active_slot();
curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
curl_easy_setopt(freq->slot->curl, CURLOPT_URL, url);
curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
/*
* If we have successfully processed data from a previous fetch
* attempt, only fetch the data we don't already have.
*/
if (prev_posn>0) {
if (http_is_verbose)
fprintf(stderr,
"Resuming fetch of object %s at byte %ld\n",
hex, prev_posn);
sprintf(range, "Range: bytes=%ld-", prev_posn);
range_header = curl_slist_append(range_header, range);
curl_easy_setopt(freq->slot->curl,
CURLOPT_HTTPHEADER, range_header);
}
return freq;
free(url);
abort:
free(filename);
free(freq);
return NULL;
}
void process_http_object_request(struct http_object_request *freq)
{
if (freq->slot == NULL)
return;
freq->curl_result = freq->slot->curl_result;
freq->http_code = freq->slot->http_code;
freq->slot = NULL;
}
int finish_http_object_request(struct http_object_request *freq)
{
struct stat st;
close(freq->localfile);
freq->localfile = -1;
process_http_object_request(freq);
if (freq->http_code == 416) {
fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
} else if (freq->curl_result != CURLE_OK) {
if (stat(freq->tmpfile, &st) == 0)
if (st.st_size == 0)
unlink_or_warn(freq->tmpfile);
return -1;
}
git_inflate_end(&freq->stream);
git_SHA1_Final(freq->real_sha1, &freq->c);
if (freq->zret != Z_STREAM_END) {
unlink_or_warn(freq->tmpfile);
return -1;
}
if (hashcmp(freq->sha1, freq->real_sha1)) {
unlink_or_warn(freq->tmpfile);
return -1;
}
freq->rename =
move_temp_to_file(freq->tmpfile, freq->filename);
return freq->rename;
}
void abort_http_object_request(struct http_object_request *freq)
{
unlink_or_warn(freq->tmpfile);
release_http_object_request(freq);
}
void release_http_object_request(struct http_object_request *freq)
{
if (freq->localfile != -1) {
close(freq->localfile);
freq->localfile = -1;
}
if (freq->url != NULL) {
free(freq->url);
freq->url = NULL;
}
freq->slot = NULL;
}
|
1ce297de93a9265e85f6bf93e36bdbaaaa366d2d | 6426efc6c9b52740cba5003556751f2b2f255f29 | /LeetCode Submissions/power-of-two/Wrong Answer/10-27-2021, 11_28_08 PM/Solution.cpp | 41698b78cab257600f36e705b2161dd2263b1062 | [] | no_license | Midas847/Competitive-Coding | d57614635fea01348c8b77952e8096b7fda536ca | 18c5e712ee6092552adac514628f362a72833d2c | refs/heads/main | 2023-09-02T15:49:40.116566 | 2021-11-21T15:38:02 | 2021-11-21T15:38:02 | 430,405,418 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 187 | cpp | Solution.cpp | // https://leetcode.com/problems/power-of-two
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n==1 || n%2 == 0)
return true;
return false;
}
}; |
c23e88e33815c57e3d6871e7a21dc3e3b476ebff | 94dbfcf94dd0a61d7cd197cf996602d5a2acdda7 | /weekly_contest/302/6122_minimum-deletions-to-make-array-divisible.cpp | 01f9fd3ca765a73e3cbdea8c7164392c2c6e5227 | [] | no_license | PengJi/Algorithms | 46ac90691cc20b0f769374ac3d848a26766965b1 | 6aa26240679bc209a6fd69580b9c7994cef51b54 | refs/heads/master | 2023-07-21T05:57:50.637703 | 2023-07-07T10:16:48 | 2023-07-09T10:17:10 | 243,935,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | cpp | 6122_minimum-deletions-to-make-array-divisible.cpp | class Solution {
public:
int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}
int minOperations(vector<int>& nums, vector<int>& numsDivide) {
int d = 0;
for(auto x : numsDivide) d = gcd(d, x);
int res = 0;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++) {
if(d % nums[i] == 0) break;
else res++;
}
if(res == nums.size()) res = -1;
return res;
}
};
|
18ddb75bc6af165a8aba98b5ce4f8e71b000bf78 | b22c769f7279cc6001b6ecc6670e4821cf46ca30 | /src/Application/SkyXHydrax/EC_SkyX.h | de848dda3688ebfa09fd190e70c7284463b0d15e | [
"Apache-2.0"
] | permissive | realXtend/tundra | 2b32127eccdd451ef9630777a808af162f8e8075 | 798112e78bfe0e425ecce6eca92a1a838cc0d1c8 | refs/heads/tundra2 | 2021-01-18T21:17:16.673031 | 2016-03-30T13:03:44 | 2016-03-30T13:03:44 | 563,197 | 33 | 20 | null | 2016-01-04T15:45:48 | 2010-03-15T12:44:26 | C++ | UTF-8 | C++ | false | false | 6,745 | h | EC_SkyX.h | /**
For conditions of distribution and use, see copyright notice in LICENSE
@file EC_SkyX.h
@brief A sky component using SkyX, http://www.ogre3d.org/tikiwiki/SkyX */
#pragma once
#include "SkyXHydraxApi.h"
#include "IComponent.h"
#include "Math/float3.h"
#include "Color.h"
namespace Ogre { class Camera; }
/// A Sky component using SkyX, http://www.ogre3d.org/tikiwiki/SkyX
/** This is a singleton type component and only one component per scene is allowed.
Provides means of creating photorealistic environments together with EC_Hydrax.
@note Requires SkyX Ogre add-on.
@note SkyX and EnvironmentLight components can be considered somewhat mutually exclusive. */
class SKYX_HYDRAX_API EC_SkyX : public IComponent
{
Q_OBJECT
COMPONENT_NAME("SkyX", 38)
public:
/// @cond PRIVATE
/// Do not directly allocate new components using operator new, but use the factory-based SceneAPI::CreateComponent functions instead.
explicit EC_SkyX(Scene* scene);
/// @endcond
~EC_SkyX();
/// Different cloud types supported by SkyX
enum CloudType
{
None, ///< Disabled.
Normal, ///< Cloud layer at fixed height above camera.
Volumetric, ///< Volumetric clouds.
};
/// Used cloud type, see CloudType.
DEFINE_QPROPERTY_ATTRIBUTE(int, cloudType);
Q_PROPERTY(int cloudType READ getcloudType WRITE setcloudType);
/// The time multiplier can be a also a negative number, 0 will disable auto-updating.
/** @note If time multiplier is altered on a headless Tundra, the changes to the time attribute
are *not* made accordingly. If you want to guarantee the same time between all participants,
do not use timeMultiplier, but instead drive the time changes manually from a script. */
DEFINE_QPROPERTY_ATTRIBUTE(float, timeMultiplier);
Q_PROPERTY(float timeMultiplier READ gettimeMultiplier WRITE settimeMultiplier);
/// Time of day in [0,24]h range.
DEFINE_QPROPERTY_ATTRIBUTE(float, time);
Q_PROPERTY(float time READ gettime WRITE settime);
/// Sunrise time in [0,24]h range.
DEFINE_QPROPERTY_ATTRIBUTE(float, sunriseTime);
Q_PROPERTY(float sunriseTime READ getsunriseTime WRITE setsunriseTime);
/// Sunset time in [0,24]h range.
DEFINE_QPROPERTY_ATTRIBUTE(float, sunsetTime);
Q_PROPERTY(float sunsetTime READ getsunsetTime WRITE setsunsetTime);
/// Cloud coverage with range [0,100] (Volumetric clouds only).
DEFINE_QPROPERTY_ATTRIBUTE(float, cloudCoverage);
Q_PROPERTY(float cloudCoverage READ getcloudCoverage WRITE setcloudCoverage);
/// Average cloud size with range [0,100] (Volumetric clouds only).
DEFINE_QPROPERTY_ATTRIBUTE(float, cloudAverageSize);
Q_PROPERTY(float cloudAverageSize READ getcloudAverageSize WRITE setcloudAverageSize);
/// The height at the clouds will reside.
DEFINE_QPROPERTY_ATTRIBUTE(float, cloudHeight);
Q_PROPERTY(float cloudHeight READ getcloudHeight WRITE setcloudHeight);
/// Moon phase with range [0,100] where 0 means fully covered moon, 50 clear moon and 100 fully covered moon.
DEFINE_QPROPERTY_ATTRIBUTE(float, moonPhase);
Q_PROPERTY(float moonPhase READ getmoonPhase WRITE setmoonPhase);
/// Sun inner radius.
DEFINE_QPROPERTY_ATTRIBUTE(float, sunInnerRadius);
Q_PROPERTY(float sunInnerRadius READ getsunInnerRadius WRITE setsunInnerRadius);
/// Sun outer radius.
DEFINE_QPROPERTY_ATTRIBUTE(float, sunOuterRadius);
Q_PROPERTY(float sunOuterRadius READ getsunOuterRadius WRITE setsunOuterRadius);
/// Wind direction, in degrees.
DEFINE_QPROPERTY_ATTRIBUTE(float, windDirection);
Q_PROPERTY(float windDirection READ getwindDirection WRITE setwindDirection);
/// Wind speed. Might need different value with normal versus volumetric clouds to actually get same speed.
DEFINE_QPROPERTY_ATTRIBUTE(float, windSpeed);
Q_PROPERTY(float windSpeed READ getwindSpeed WRITE setwindSpeed);
/// Diffuse color of the sunlight.
DEFINE_QPROPERTY_ATTRIBUTE(Color, sunlightDiffuseColor);
Q_PROPERTY(Color sunlightDiffuseColor READ getsunlightDiffuseColor WRITE setsunlightDiffuseColor);
/// Specular color of the sunlight.
DEFINE_QPROPERTY_ATTRIBUTE(Color, sunlightSpecularColor);
Q_PROPERTY(Color sunlightSpecularColor READ getsunlightSpecularColor WRITE setsunlightSpecularColor);
/// Diffuse color of the moonlight.
DEFINE_QPROPERTY_ATTRIBUTE(Color, moonlightDiffuseColor);
Q_PROPERTY(Color moonlightDiffuseColor READ getmoonlightDiffuseColor WRITE setmoonlightDiffuseColor);
/// Specular color of the moonlight.
DEFINE_QPROPERTY_ATTRIBUTE(Color, moonlightSpecularColor);
Q_PROPERTY(Color moonlightSpecularColor READ getmoonlightSpecularColor WRITE setmoonlightSpecularColor);
/// Scene's ambient light color.
DEFINE_QPROPERTY_ATTRIBUTE(Color, ambientLightColor);
Q_PROPERTY(Color ambientLightColor READ getambientLightColor WRITE setambientLightColor);
public slots:
/// Returns whether or not the sun is visible (above horizon).
bool IsSunVisible() const;
/// Returns position of the sun, or nan if not applicable.
float3 SunPosition() const;
/// Returns Earth-to-Sun direction of the sun, or nan if not applicable.
float3 SunDirection() const;
/// Returns whether or not the moon is visible (above horizon).
bool IsMoonVisible() const;
/// Returns position of the moon, or nan if not applicable.
float3 MoonPosition() const;
/// Returns Earth-to-Moon direction of the moon, or nan if not applicable.
float3 MoonDirection() const;
private slots:
void Create();
void OnActiveCameraChanged(Entity *camEntity);
void UpdateAttribute(IAttribute *attr, AttributeChange::Type change);
void Update(float frameTime);
private:
struct Impl;
Impl *impl;
void Remove();
void CreateLights();
void RegisterListeners();
void UnregisterListeners();
void UpdateLightsAndPositions();
// VCloudManager register/unregister functions.
// If input camera is null, Tundra's active camera is used.
void RegisterCamera(Ogre::Camera *camera = 0); /**< @todo SkyX internal logic, move to Impl. */
void UnregisterCamera(Ogre::Camera *camera = 0); /**< @todo SkyX internal logic, move to Impl. */
void HandleVCloudsCamera(Ogre::Camera *camera, bool registerCamera); /**< @todo SkyX internal logic, move to Impl. */
void ApplyAtmosphereOptions();
void UnloadNormalClouds(); /**< @todo SkyX internal logic, move to Impl. */
void UnloadVolumetricClouds(); /**< @todo SkyX internal logic, move to Impl. */
Ogre::Camera *FindOgreCamera(Entity *cameraEntity) const;
};
|
39d732787186245ac03fb930ee90a313bb2d3882 | 314c8b50befaa23f0a95320f97ca2961a1904614 | /c++pp/c++pratice/STL/test_map.cpp | 8e0ffce1209de21e3c89509d3d4f73762564226e | [] | no_license | hchc32/linux-hc | c9f86d338419ea047ae2efae7b31104dfcac9261 | 35108133a3ea1f5fa7a8ca4a1e850566503e4237 | refs/heads/master | 2023-03-01T17:10:14.092615 | 2021-08-06T23:19:14 | 2021-08-06T23:19:14 | 226,843,078 | 0 | 0 | null | 2023-02-25T08:18:10 | 2019-12-09T10:18:16 | Go | UTF-8 | C++ | false | false | 564 | cpp | test_map.cpp | #include<iostream>
template<class Key,
class T,
class Compare = less<Key>,
class Alloc = alloc
>
class map
{
public:
typedef Key Key_type;
typedef T data_type;
typedef T mapped_type;
//const Key,key不能用迭代器更改,data可以.
typedef pair<const Key,T> value_type;
typedef Compare Key_compare;
private:
//红黑树
typedef rb_tree<Key_type,value_type,select1st<value_type>,Key_compare,Alloc> rep_type;
rep_type t;
public:
typedef typename rep_type::iterator iterator;
...
};
|
16e74588e4192ed3a8d8adc689fc5fcdbdc0bfc9 | 7b75de6417e23b6ca0cdc1e47c28a5c48d237e57 | /OpenGL-Triangle/MyRender.h | 6fbea68be1d91e38270861d4af3d8ae7692c8115 | [] | no_license | zhangqiang880/OpenGL-Totural | 29f02a92d9d9f453f81f76ffb624c27bc258e252 | 30be5c1a8b6ee72d6c1fc3033db6dbbf2cd60f94 | refs/heads/master | 2022-02-20T15:41:19.039859 | 2019-09-03T12:41:57 | 2019-09-03T12:41:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | h | MyRender.h | #ifndef MYRENDER_H
#define MYRENDER_H
#include "OpenGLRender.h"
#include <glm/vec3.hpp>
#include <glm/mat4x4.hpp>
class MyRender : public OpenGLRender
{
public:
MyRender();
~MyRender();
void render();
void resizeGL(int w, int h);
void initializeGL();
void initializeShader();
void initializeTriangle();
private:
GLuint m_vbo;
GLuint m_program;
glm::mat4x4 m_projection;
};
#endif
|
220c7d1d10a41c6aa33b52e43085d66c0156be36 | 375d4b5bd3dffb5475754db5fd619469cb07c671 | /src/04_trees_and_graphs/check_subtree.cpp | e43039686b0822fe1e08c62d59d5b59ea65f7053 | [] | no_license | CarlosAlmeida4/cracking-coding | 0f8d43409c6b9766f5b053792f84ec62b9d3d6f7 | ad324269015560ea8b7e02eb40e726f34a168be4 | refs/heads/master | 2023-04-09T04:32:14.034425 | 2021-04-11T11:45:58 | 2021-04-11T11:45:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,446 | cpp | check_subtree.cpp | // Check Subtree: T1 and T2 are two very large binary trees, with Tl much bigger
// than T2. Create an algorith m to determine if T2 is a subtree of Tl . A tree
// T2 is a subtree ofTi if there exists a node n in Ti such that the subtree of
// n is identical to T2. That is, if you cut off the tree at node n, the two
// trees would be identical. Hints: #4, #11, #18, #31, #37
#include <string>
#include "utils/tree.h"
using namespace utils;
// Solution #1
// Complexity: time O(n + m), space O(n + m), where n and m are the number of
// nodes in T1 and T2, respectively.
// ------------------------------------------------------------------------------------------------
void getOrderstring(TreeNodePtr node, std::string &s) {
if (node == nullptr) {
s.append("X"); // Add null indicator
return;
}
s.append(std::to_string(node->value)); // Add root
getOrderstring(node->left, s); // Add left
getOrderstring(node->right, s); // Add right
}
bool containsTree_1(TreeNodePtr t1, TreeNodePtr t2) {
std::string string1;
std::string string2;
getOrderstring(t1, string1);
getOrderstring(t2, string2);
return string1.find(string2) != std::string::npos;
}
// Solution #2
// Complexity: time O(n + km), space O(lon(n) + log(m)), where k is the number
// of occurrences of T2's root in T1.
// ------------------------------------------------------------------------------------------------
bool matchTree(TreeNodePtr r1, TreeNodePtr r2) {
if (r1 == nullptr && r2 == nullptr) {
return true; // nothing left in the subtree
} else if (r1 == nullptr || r2 == nullptr) {
return false; // exactly tree is empty, therefore trees don't match
} else if (r1->value != r2->value) {
return false; // data doesn't match
} else {
return matchTree(r1->left, r2->left) && matchTree(r1->right, r2->right);
}
}
bool subTree(TreeNodePtr r1, TreeNodePtr r2) {
if (r1 == nullptr) {
return false; // big tree empty & subtree still not found
} else if (r1->value == r2->value && matchTree(r1, r2)) {
return true;
}
return subTree(r1->left, r2) || subTree(r1->right, r2);
}
bool containsTree_2(TreeNodePtr t1, TreeNodePtr t2) {
if (t2 == nullptr)
return true; // The empty tree is always a subtree
return subTree(t1, t2);
}
// Test
// ------------------------------------------------------------------------------------------------
#include "gtest/gtest.h"
TEST(CheckSubtreeTest, Trivial) {
// t1 tree
// (0)
// / \
// (1) (2)
// / \
// (3) (4)
// /
// (5)
auto t1 = std::make_shared<TreeNode>(0);
t1->left = std::make_shared<TreeNode>(1);
t1->right = std::make_shared<TreeNode>(2);
t1->left->left = std::make_shared<TreeNode>(3);
t1->left->right = std::make_shared<TreeNode>(4);
t1->left->left->left = std::make_shared<TreeNode>(5);
// t2 tree
// (1)
// / \
// (3) (4)
auto t2 = std::make_shared<TreeNode>(1);
t2->left = std::make_shared<TreeNode>(3);
t2->right = std::make_shared<TreeNode>(4);
EXPECT_FALSE(containsTree_1(t1, t2));
EXPECT_FALSE(containsTree_2(t1, t2));
// t2 becomes ->
// (1)
// / \
// (3) (4)
// /
// (5)
t2->left->left = std::make_shared<TreeNode>(5);
EXPECT_TRUE(containsTree_1(t1, t2));
EXPECT_TRUE(containsTree_2(t1, t2));
}
|
e8292252ce7aaa27ff1edb635f9a7a9c0f2bfef4 | bbb4d35c4004a8b0fde152bc7b8699fdf4f244ab | /max1.cpp | 33d47023e87ec48bf8f4b1dd60207d3480f35182 | [] | no_license | Manisha-nitd/OOPS-and-DATA-STRUCTURE | 52338eaa27c619c81fe8b4651d98c308e81213f2 | 72301905819ac45cad5b66ffa38daa164469300f | refs/heads/master | 2021-09-09T02:02:05.335795 | 2018-03-13T08:55:09 | 2018-03-13T08:55:09 | 125,021,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,330 | cpp | max1.cpp | #include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int row,column;
int **a,*b;
int count=0,max=0,flag=0;
a=new int*[row];
b=new int[row];
cout<<" :PROGRAM TO CHECK ROW FOR MAXIMUM NUMBER OF 1'S :";
cout<<"\n\nEnter the matrix diension(row then column) :"<<endl;
cin>>row>>column;
cout<<"Enter the matrix value:"<<endl;
for(int i=0;i<row;i++)
{
*(a+i)=new int[column];
for(int j=0;j<column;j++)
cin>>a[i][j];
}
for(int i=0;i<row;i++)
{
count=0;
for(int j=0;j<column;j++)
{
if(a[i][j]==1)
{
count++;
flag=1;
}
}
b[i]=count;//to store the number of 1's in each row.
if(count>max)
max=count;
}
cout<<"\n\nDisplaying the matrix :"<<endl;
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
cout<<" "<<a[i][j];
cout<<endl;
}
if(flag)
{
cout<<"\nThe maximum number of 1 is in the row :";
for(int i=0;i<row;i++)
{
if(b[i]==max)//more than one row may have maximum number of 1's.
cout<<" "<<i+1;
}
}
else
cout<<"\n\nNO '1's are present !!"<<endl;
return 0;
}
|
314228c9631e7b91c1d032a2839414b74c0dc28c | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model.cc | 2ed486ea98562f8eeee6b427f169c38b72af12dc | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 12,057 | cc | settings_reset_prompt_model.cc | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_model.h"
#include <utility>
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profile_resetter/brandcoded_default_settings.h"
#include "chrome/browser/profile_resetter/profile_resetter.h"
#include "chrome/browser/profile_resetter/resettable_settings_snapshot.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_config.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/common/extensions/manifest_handlers/settings_overrides_handler.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/search_engines/template_url_service.h"
#include "components/url_formatter/url_fixer.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_id.h"
namespace safe_browsing {
namespace {
// These values are used for UMA metrics reporting. New enum values can be
// added, but existing enums must never be renumbered or deleted and reused.
enum SettingsReset {
SETTINGS_RESET_HOMEPAGE = 1,
SETTINGS_RESET_DEFAULT_SEARCH = 2,
SETTINGS_RESET_STARTUP_URLS = 3,
SETTINGS_RESET_MAX,
};
// Used to keep track of which settings types have been initialized in
// |SettingsResetPromptModel|.
enum SettingsType : uint32_t {
SETTINGS_TYPE_HOMEPAGE = 1 << 0,
SETTINGS_TYPE_DEFAULT_SEARCH = 1 << 1,
SETTINGS_TYPE_STARTUP_URLS = 1 << 2,
SETTINGS_TYPE_ALL = SETTINGS_TYPE_HOMEPAGE | SETTINGS_TYPE_DEFAULT_SEARCH |
SETTINGS_TYPE_STARTUP_URLS,
};
const extensions::Extension* GetExtension(
Profile* profile,
const extensions::ExtensionId& extension_id) {
return extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(
extension_id);
}
GURL FixupUrl(const std::string& url_text) {
return url_formatter::FixupURL(url_text, /*desired_tld=*/std::string());
}
} // namespace
SettingsResetPromptModel::SettingsResetPromptModel(
Profile* profile,
std::unique_ptr<SettingsResetPromptConfig> prompt_config,
std::unique_ptr<ProfileResetter> profile_resetter)
: profile_(profile),
prefs_manager_(profile, prompt_config->prompt_wave()),
prompt_config_(std::move(prompt_config)),
settings_snapshot_(std::make_unique<ResettableSettingsSnapshot>(profile)),
profile_resetter_(std::move(profile_resetter)),
time_since_last_prompt_(base::Time::Now() -
prefs_manager_.LastTriggeredPrompt()) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(profile_);
DCHECK(prompt_config_);
DCHECK(settings_snapshot_);
DCHECK(profile_resetter_);
InitDefaultSearchData();
InitStartupUrlsData();
InitHomepageData();
DCHECK_EQ(settings_types_initialized_, SETTINGS_TYPE_ALL);
BlockResetForSettingOverridenByExtension();
if (!SomeSettingRequiresReset())
return;
// For now, during the experimental phase, if policy controls any of the
// settings that we consider for reset (search, startup pages, homepage) or if
// an extension that needs to be disabled is managed by policy, then we do not
// show the reset prompt.
//
// TODO(alito): Consider how clients with policies should be prompted for
// reset.
if (SomeSettingIsManaged()) {
if (homepage_reset_state_ == RESET_REQUIRED)
homepage_reset_state_ = NO_RESET_REQUIRED_DUE_TO_POLICY;
if (default_search_reset_state_ == RESET_REQUIRED)
default_search_reset_state_ = NO_RESET_REQUIRED_DUE_TO_POLICY;
if (startup_urls_reset_state_ == RESET_REQUIRED)
startup_urls_reset_state_ = NO_RESET_REQUIRED_DUE_TO_POLICY;
}
}
SettingsResetPromptModel::~SettingsResetPromptModel() {}
Profile* SettingsResetPromptModel::profile() const {
return profile_;
}
SettingsResetPromptConfig* SettingsResetPromptModel::config() const {
return prompt_config_.get();
}
bool SettingsResetPromptModel::ShouldPromptForReset() const {
return SomeSettingRequiresReset();
}
void SettingsResetPromptModel::PerformReset(
std::unique_ptr<BrandcodedDefaultSettings> default_settings,
base::OnceClosure done_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(default_settings);
// Disable all the settings that need to be reset.
ProfileResetter::ResettableFlags reset_flags = 0;
if (homepage_reset_state() == RESET_REQUIRED) {
reset_flags |= ProfileResetter::HOMEPAGE;
}
if (default_search_reset_state() == RESET_REQUIRED) {
reset_flags |= ProfileResetter::DEFAULT_SEARCH_ENGINE;
}
if (startup_urls_reset_state() == RESET_REQUIRED) {
reset_flags |= ProfileResetter::STARTUP_PAGES;
}
profile_resetter_->Reset(reset_flags, std::move(default_settings),
std::move(done_callback));
}
void SettingsResetPromptModel::DialogShown() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(SomeSettingRequiresReset());
base::Time now = base::Time::Now();
if (default_search_reset_state() == RESET_REQUIRED)
prefs_manager_.RecordPromptShownForDefaultSearch(now);
if (startup_urls_reset_state() == RESET_REQUIRED)
prefs_manager_.RecordPromptShownForStartupUrls(now);
if (homepage_reset_state() == RESET_REQUIRED)
prefs_manager_.RecordPromptShownForHomepage(now);
}
GURL SettingsResetPromptModel::homepage() const {
return homepage_url_;
}
SettingsResetPromptModel::ResetState
SettingsResetPromptModel::homepage_reset_state() const {
DCHECK(homepage_reset_state_ != RESET_REQUIRED ||
homepage_reset_domain_id_ >= 0);
return homepage_reset_state_;
}
GURL SettingsResetPromptModel::default_search() const {
return default_search_url_;
}
SettingsResetPromptModel::ResetState
SettingsResetPromptModel::default_search_reset_state() const {
DCHECK(default_search_reset_state_ != RESET_REQUIRED ||
default_search_reset_domain_id_ >= 0);
return default_search_reset_state_;
}
const std::vector<GURL>& SettingsResetPromptModel::startup_urls() const {
return startup_urls_;
}
const std::vector<GURL>& SettingsResetPromptModel::startup_urls_to_reset()
const {
return startup_urls_to_reset_;
}
SettingsResetPromptModel::ResetState
SettingsResetPromptModel::startup_urls_reset_state() const {
return startup_urls_reset_state_;
}
void SettingsResetPromptModel::InitDefaultSearchData() {
// Default search data must be the first setting type to be initialized.
DCHECK_EQ(settings_types_initialized_, 0U);
settings_types_initialized_ |= SETTINGS_TYPE_DEFAULT_SEARCH;
default_search_url_ = FixupUrl(settings_snapshot_->dse_url());
default_search_reset_domain_id_ =
prompt_config_->UrlToResetDomainId(default_search_url_);
if (default_search_reset_domain_id_ < 0)
return;
default_search_reset_state_ = GetResetStateForSetting(
prefs_manager_.LastTriggeredPromptForDefaultSearch());
}
void SettingsResetPromptModel::InitStartupUrlsData() {
// Default search data must have been initialized before startup URLs data.
DCHECK_EQ(settings_types_initialized_, SETTINGS_TYPE_DEFAULT_SEARCH);
settings_types_initialized_ |= SETTINGS_TYPE_STARTUP_URLS;
// Only the url restoring startup types are candidates for resetting.
if (!SessionStartupPref(settings_snapshot_->startup_type()).ShouldOpenUrls())
return;
for (const GURL& startup_url : settings_snapshot_->startup_urls()) {
GURL fixed_url = FixupUrl(startup_url.possibly_invalid_spec());
startup_urls_.push_back(fixed_url);
int reset_domain_id = prompt_config_->UrlToResetDomainId(fixed_url);
if (reset_domain_id >= 0) {
startup_urls_to_reset_.push_back(fixed_url);
domain_ids_for_startup_urls_to_reset_.insert(reset_domain_id);
}
}
if (startup_urls_to_reset_.empty())
return;
startup_urls_reset_state_ = GetResetStateForSetting(
prefs_manager_.LastTriggeredPromptForStartupUrls());
}
void SettingsResetPromptModel::InitHomepageData() {
// Homepage data must be initialized after default search and startup URLs
// data.
DCHECK_EQ(settings_types_initialized_,
SETTINGS_TYPE_DEFAULT_SEARCH | SETTINGS_TYPE_STARTUP_URLS);
settings_types_initialized_ |= SETTINGS_TYPE_HOMEPAGE;
homepage_url_ = FixupUrl(settings_snapshot_->homepage());
// If the home button is not visible to the user, then the homepage setting
// has no real user-visible effect.
if (!settings_snapshot_->show_home_button())
return;
// We do not currently support resetting New Tab pages that are set by
// extensions.
if (settings_snapshot_->homepage_is_ntp())
return;
homepage_reset_domain_id_ = prompt_config_->UrlToResetDomainId(homepage_url_);
if (homepage_reset_domain_id_ < 0)
return;
homepage_reset_state_ =
GetResetStateForSetting(prefs_manager_.LastTriggeredPromptForHomepage());
}
// Reverts the decision to reset some setting if it's overriden by an extension.
// This function should be called after other Init*() functions.
void SettingsResetPromptModel::BlockResetForSettingOverridenByExtension() {
DCHECK_EQ(settings_types_initialized_, SETTINGS_TYPE_ALL);
// |enabled_extensions()| is a container of [id, name] pairs.
for (const auto& id_name : settings_snapshot_->enabled_extensions()) {
const extensions::Extension* extension =
GetExtension(profile_, id_name.first);
if (!extension)
continue;
const extensions::SettingsOverrides* overrides =
extensions::SettingsOverrides::Get(extension);
if (!overrides)
continue;
if (homepage_reset_state_ == RESET_REQUIRED && overrides->homepage)
homepage_reset_state_ = NO_RESET_REQUIRED_DUE_TO_EXTENSION_OVERRIDE;
if (default_search_reset_state_ == RESET_REQUIRED &&
overrides->search_engine) {
default_search_reset_state_ = NO_RESET_REQUIRED_DUE_TO_EXTENSION_OVERRIDE;
}
if (startup_urls_reset_state_ == RESET_REQUIRED &&
!overrides->startup_pages.empty()) {
startup_urls_reset_state_ = NO_RESET_REQUIRED_DUE_TO_EXTENSION_OVERRIDE;
}
}
}
SettingsResetPromptModel::ResetState
SettingsResetPromptModel::GetResetStateForSetting(
const base::Time& last_triggered_for_setting) const {
if (!last_triggered_for_setting.is_null())
return NO_RESET_REQUIRED_DUE_TO_ALREADY_PROMPTED_FOR_SETTING;
if (time_since_last_prompt_ < prompt_config_->time_between_prompts())
return NO_RESET_REQUIRED_DUE_TO_RECENTLY_PROMPTED;
if (SomeSettingRequiresReset())
return NO_RESET_REQUIRED_DUE_TO_OTHER_SETTING_REQUIRING_RESET;
return RESET_REQUIRED;
}
bool SettingsResetPromptModel::SomeSettingRequiresReset() const {
return default_search_reset_state_ == RESET_REQUIRED ||
startup_urls_reset_state_ == RESET_REQUIRED ||
homepage_reset_state_ == RESET_REQUIRED;
}
bool SettingsResetPromptModel::SomeSettingIsManaged() const {
PrefService* prefs = profile_->GetPrefs();
DCHECK(prefs);
// Check if homepage is managed.
const PrefService::Preference* homepage =
prefs->FindPreference(prefs::kHomePage);
if (homepage && (homepage->IsManaged() || homepage->IsManagedByCustodian()))
return true;
// Check if startup pages are managed.
if (SessionStartupPref::TypeIsManaged(prefs) ||
SessionStartupPref::URLsAreManaged(prefs)) {
return true;
}
// Check if default search is managed.
TemplateURLService* service =
TemplateURLServiceFactory::GetForProfile(profile_);
if (service && service->is_default_search_managed())
return true;
return false;
}
} // namespace safe_browsing.
|
bbe469783feead0c5569fa264e74c3261eb397af | bb50fe254cf2025433f79392ade6353511430c4e | /ACM-ICPC/AlBaathCPC2015/Traffic Lights.cpp | 1f0af7274261609e2871c5b510312e25ec20ceef | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | AlyShmahell/AlyShmahell-CompetitiveProgramming | 7bfc5ffbcfaf28aab94d687c848bcd9c03566abc | cd25c1cfe87603f5402db4ca9d69719fbd4a8e0d | refs/heads/master | 2020-03-22T00:52:00.781581 | 2018-06-30T19:30:09 | 2018-06-30T19:30:09 | 139,269,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,517 | cpp | Traffic Lights.cpp | /*
Copyright (c) 2016 Aly Shmahell
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation is required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
long long int x,g,y,r,value,values[3],temp;
string colors[3]= {"GREEN","YELLOW","RED"};
cin>>t;
while(t--)
{
cin>>x>>g>>y>>r;
x++;
values[0]=g;
values[1]=y;
values[2]=r;
value = 0;
while(x>=0)
{
temp = values[value%3];
if(x-temp>=0)
x-=temp;
else
{
cout<<colors[value%3];
if(t)
cout<<endl;
break;
}
value++;
}
}
}
|
78c8416892ea928e738f0fccb5740f5c2d68e35f | 444a6f3fb2c9d9dc042ffd54838bc3dc172ec531 | /example/alternative_namespaces/force.h | ad0945e5d41e4f3b864aa6c26fbded89057a7f48 | [
"MIT"
] | permissive | rtobar/units | ef5a86bdb73c896eac92698d9a8386e11c6dfe48 | 5dd9eaac87a50adc62b170987ebac2d1344d63c5 | refs/heads/master | 2022-09-11T17:37:57.868428 | 2020-05-24T20:49:53 | 2020-05-24T20:49:53 | 266,679,421 | 1 | 0 | MIT | 2020-05-25T04:03:18 | 2020-05-25T04:03:18 | null | UTF-8 | C++ | false | false | 248 | h | force.h |
#pragma once
#include <units/physical/si/force.h>
namespace units{
namespace experimental{
namespace force {
template<typename Rep = double>
using N = units::physical::si::force<units::physical::si::newton, Rep>;
}
}} // units::experimental
|
bf6aa7220896b53418b2ab0b5b14e2e09defbce9 | 1f8e80f4a35f3100f442d3b044b90e530b5ca2aa | /Project2/Project 2 - Complex Number Class ObjOverload/complex.cpp | 6a181d12d1f65cf88321fb006c68cbf5ad523ecb | [] | no_license | KrickLogan/CSCI301Projects | 1d4905db84f3c25588c9781d94b073b695369bd9 | a238bc03f771ca087bae2b054b4fb717fad7fb87 | refs/heads/main | 2023-07-13T18:46:53.394237 | 2021-08-23T23:32:29 | 2021-08-23T23:32:29 | 399,274,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | complex.cpp | /*
Author: Logan Krick
Course and Section: CSCI 301 Sec 1
StarID: pq8748xu
File Location on the server:
Due Date: 9/13/18
Instructor: Jie Hu Meichsner
*/
#include <iostream>
#include "complex.h"
complex::complex(double initial_real, double initial_imag)
{
real = initial_real;
imag = initial_imag;
}
ostream& operator<<(ostream& out, const complex& c) {
out << c.real << " + " << c.imag << "i" << endl;
return out;
}
istream& operator>>(istream& in, complex& c) {
in >> c.real >> c.imag;
return in;
}
|
03667422a970847e660cfa79a5ae27e4edb9efde | d9e96244515264268d6078650fa707f34d94ee7a | /Assets/BlockSerializer.h | d68b5f4faeecfee60ef76cea9c197ab123719b08 | [
"MIT"
] | permissive | xlgames-inc/XLE | 45c89537c10561e216367a2e3bcd7d1c92b1b039 | 69cc4f2aa4faf12ed15bb4291c6992c83597899c | refs/heads/master | 2022-06-29T17:16:11.491925 | 2022-05-04T00:29:28 | 2022-05-04T00:29:28 | 29,281,799 | 396 | 102 | null | 2016-01-04T13:35:59 | 2015-01-15T05:07:55 | C++ | UTF-8 | C++ | false | false | 9,531 | h | BlockSerializer.h | // Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#pragma once
#include "../Core/Types.h"
#include "../Core/Exceptions.h"
#include "../Math/Vector.h"
#include "../Math/Matrix.h"
#include "../Utility/PtrUtils.h"
#include <vector>
#include <iterator>
#include <type_traits>
namespace Serialization
{
////////////////////////////////////////////////////
class NascentBlockSerializer
{
public:
struct SpecialBuffer
{
enum Enum { Unknown, VertexBuffer, IndexBuffer, String, Vector, UniquePtr };
};
template<typename Type> void SerializeSubBlock(const Type* type);
template<typename Type, typename std::enable_if< !std::is_pod<Type>::value >::type* = nullptr>
void SerializeSubBlock(const Type* begin, const Type* end, SpecialBuffer::Enum specialBuffer = SpecialBuffer::Unknown);
template<typename Type, typename std::enable_if< std::is_pod<Type>::value >::type* = nullptr>
void SerializeSubBlock(const Type* begin, const Type* end, SpecialBuffer::Enum specialBuffer = SpecialBuffer::Unknown);
void SerializeSubBlock(NascentBlockSerializer& subBlock, SpecialBuffer::Enum specialBuffer = SpecialBuffer::Unknown);
void SerializeRawSubBlock(const void* begin, const void* end, SpecialBuffer::Enum specialBuffer = SpecialBuffer::Unknown);
void SerializeSpecialBuffer( SpecialBuffer::Enum specialBuffer,
const void* begin, const void* end);
void SerializeValue ( uint8 value );
void SerializeValue ( uint16 value );
void SerializeValue ( uint32 value );
void SerializeValue ( uint64 value );
void SerializeValue ( float value );
void SerializeValue ( const std::string& value );
void AddPadding ( unsigned sizeInBytes );
template<typename Type, typename Allocator>
void SerializeValue ( const std::vector<Type, Allocator>& value );
template<typename Type, typename Deletor>
void SerializeValue ( const DynamicArray<Type, Deletor>& value );
template<typename Type, typename Deletor>
void SerializeValue ( const std::unique_ptr<Type, Deletor>& value, size_t count );
template<typename Type, typename Allocator>
void SerializeRaw ( const std::vector<Type, Allocator>& value );
template<typename Type>
void SerializeRaw ( Type type );
std::unique_ptr<uint8[]> AsMemoryBlock() const;
size_t Size() const;
NascentBlockSerializer();
~NascentBlockSerializer();
class InternalPointer
{
public:
size_t _pointerOffset;
size_t _subBlockOffset;
size_t _subBlockSize;
SpecialBuffer::Enum _specialBuffer;
};
static const size_t PtrFlagBit = size_t(1)<<(size_t(sizeof(size_t)*8-1));
static const size_t PtrMask = ~PtrFlagBit;
protected:
std::vector<uint8> _memory;
std::vector<uint8> _trailingSubBlocks;
std::vector<InternalPointer> _internalPointers;
void PushBackPointer(size_t value);
void PushBackRaw(const void* data, size_t size);
void PushBackRaw_SubBlock(const void* data, size_t size);
void RegisterInternalPointer(const InternalPointer& ptr);
void PushBackPlaceholder(SpecialBuffer::Enum specialBuffer);
};
void Block_Initialize(void* block, const void* base=nullptr);
const void* Block_GetFirstObject(const void* blockStart);
size_t Block_GetSize(const void* block);
std::unique_ptr<uint8[]> Block_Duplicate(const void* block);
////////////////////////////////////////////////////
template<typename Type, typename std::enable_if< !std::is_pod<Type>::value >::type*>
void NascentBlockSerializer::SerializeSubBlock(const Type* begin, const Type* end, SpecialBuffer::Enum specialBuffer)
{
NascentBlockSerializer temporaryBlock;
for (auto i=begin; i!=end; ++i) {
Serialize(temporaryBlock, *i);
}
SerializeSubBlock(temporaryBlock, specialBuffer);
}
template<typename Type, typename std::enable_if< std::is_pod<Type>::value >::type*>
void NascentBlockSerializer::SerializeSubBlock(const Type* begin, const Type* end, SpecialBuffer::Enum specialBuffer)
{
SerializeRawSubBlock((const void*)begin, (const void*)end, specialBuffer);
}
template<typename Type>
void NascentBlockSerializer::SerializeSubBlock(const Type* type)
{
NascentBlockSerializer temporaryBlock;
Serialize(temporaryBlock, type);
SerializeSubBlock(temporaryBlock, SpecialBuffer::Unknown);
}
template<typename Type, typename Allocator>
void NascentBlockSerializer::SerializeRaw(const std::vector<Type, Allocator>& vector)
{
// serialize the vector using just a raw copy of the contents
SerializeRawSubBlock(
AsPointer(vector.cbegin()), AsPointer(vector.cend()),
Serialization::NascentBlockSerializer::SpecialBuffer::Vector);
}
template<typename Type>
void NascentBlockSerializer::SerializeRaw(Type type)
{
PushBackRaw(&type, sizeof(Type));
}
template<typename Type, typename Allocator>
void NascentBlockSerializer::SerializeValue ( const std::vector<Type, Allocator>& value )
{
SerializeSubBlock(AsPointer(value.cbegin()), AsPointer(value.cend()), SpecialBuffer::Vector);
}
template<typename Type, typename Deletor>
void NascentBlockSerializer::SerializeValue ( const DynamicArray<Type, Deletor>& value )
{
SerializeSubBlock(value.begin(), value.end(), SpecialBuffer::UniquePtr);
SerializeValue(value.size());
}
template<typename Type, typename Deletor>
void NascentBlockSerializer::SerializeValue ( const std::unique_ptr<Type, Deletor>& value, size_t count )
{
SerializeSubBlock(value.get(), &value[count], SpecialBuffer::UniquePtr);
}
////////////////////////////////////////////////////
namespace Internal
{
template<typename T> struct HasSerialize
{
template<typename U, void (U::*)(NascentBlockSerializer&) const> struct FunctionSignature {};
template<typename U> static std::true_type Test1(FunctionSignature<U, &U::Serialize>*);
template<typename U> static std::false_type Test1(...);
static const bool Result = decltype(Test1<T>(0))::value;
};
template<typename T> struct IsValueType
{
template<typename U, void (NascentBlockSerializer::*)(U)> struct FunctionSignature {};
template<typename U> static std::true_type Test1(FunctionSignature<U, &NascentBlockSerializer::SerializeValue>*);
template<typename U> static std::false_type Test1(...);
static const bool Result = decltype(Test1<T>(0))::value | decltype(Test1<const T&>(0))::value;
};
}
}
template<typename Type, typename std::enable_if<Serialization::Internal::HasSerialize<Type>::Result>::type* = nullptr>
void Serialize(Serialization::NascentBlockSerializer& serializer, const Type& value)
{ value.Serialize(serializer); }
template <typename Type, typename std::enable_if<Serialization::Internal::IsValueType<Type>::Result>::type* = nullptr>
void Serialize(Serialization::NascentBlockSerializer& serializer, const Type& value)
{ serializer.SerializeValue(value); }
template<typename TypeLHS, typename TypeRHS>
void Serialize(Serialization::NascentBlockSerializer& serializer, const std::pair<TypeLHS, TypeRHS>& value)
{
Serialize(serializer, value.first);
Serialize(serializer, value.second);
const auto padding = sizeof(typename std::pair<TypeLHS, TypeRHS>) - sizeof(TypeLHS) - sizeof(TypeRHS);
if (constant_expression<(padding > 0)>::result()) {
serializer.AddPadding(padding);
}
}
template<typename Type, typename Deletor>
void Serialize(Serialization::NascentBlockSerializer& serializer, const std::unique_ptr<Type, Deletor>& value, size_t count)
{ serializer.SerializeValue(value, count); }
template<int Dimen, typename Primitive>
inline void Serialize( Serialization::NascentBlockSerializer& serializer,
const cml::vector< Primitive, cml::fixed<Dimen> >& vec)
{
for (unsigned j=0; j<Dimen; ++j) {
Serialize(serializer, vec[j]);
}
}
inline void Serialize( Serialization::NascentBlockSerializer& serializer,
const ::XLEMath::Float4x4& float4x4)
{
for (unsigned i=0; i<4; ++i)
for (unsigned j=0; j<4; ++j) {
Serialize(serializer, float4x4(i,j));
}
}
// the following has no implementation. Objects that don't match will attempt to use this implementation
void Serialize(Serialization::NascentBlockSerializer& serializer, ...) = delete;
|
b9c12efc693ae2e94b7b180aba9db568a93368b6 | da3c59e9e54b5974648828ec76f0333728fa4f0c | /mobilemessaging/audiomsg/inc/audiomessageprogressdialog.h | 069905b40d86de3399de8a44518dbbbdd32b5d81 | [] | no_license | finding-out/oss.FCL.sf.app.messaging | 552a95b08cbff735d7f347a1e6af69fc427f91e8 | 7ecf4269c53f5b2c6a47f3596e77e2bb75c1700c | refs/heads/master | 2022-01-29T12:14:56.118254 | 2010-11-03T20:32:03 | 2010-11-03T20:32:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,641 | h | audiomessageprogressdialog.h | /*
* Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Class that handles voice progressdialog operations.
*
*/
#ifndef AUDIOMESSAGEPROGRESSDIALOG_H
#define AUDIOMESSAGEPROGRESSDIALOG_H
#include <e32base.h>
#include <AknProgressDialog.h>
#include <notecontrol.h>
#include <remconcoreapitargetobserver.h>
#include <e32debug.h>
#include "amsvoiceobserver.h"
#include <AknNaviDecoratorObserver.h>
class CAudioMessageRecorder;
class MAmsVolumeObserver;
class CRemConInterfaceSelector;
class CRemConCoreApiTarget;
class CAknVolumePopup;
class CAudioMessageDocument;
/**
* Shows dialog with progressbar, states and time of duration.
* Controls recording and playing via AudioMessageRecoder object
*
* @lib audiomessage.exe
* @since S60 v3.1
*/
class CAudioMessageProgressDialog : public CAknProgressDialog,
public MAmsVoiceObserver,
public MRemConCoreApiTargetObserver,
public MAknNaviDecoratorObserver
{
protected:
enum TAmsProgressFlags
{
EAmsWorkingModeRecorder = 0x1,
EAmsSetExit = 0x2,
EAmsWsEventStop = 0x4,
EAmsPause = 0x8,
EAmsSupportAudioOutput = 0x10,
EAmsAudioOutputEarpiece = 0x20
};
public: // Constructors and destructor
/**
* Constructor
*/
CAudioMessageProgressDialog( CAudioMessageDocument& aDocument);
/**
* Destructor
*/
virtual ~CAudioMessageProgressDialog();
/**
* Factory function to create this object
*
* @param aFile filehandle for voice
* @param aVolume volume level
* @param aSpeakerEarpiece speaker ETrue earpiece
* @param aRecorder, record or play working mode
*/
static CAudioMessageProgressDialog* NewL( const RFile& aFile, TInt aVolume,
TBool aSpeakerEarpiece, TBool aRecorder, CAudioMessageDocument& aDocument);
/**
* set observer for navipane use
*/
void SetNaviObserver( MAmsVolumeObserver* aObserver );
/**
* set mode of progressdialog
* @param ETrue recoding, EFalse playing
*/
// void SetMode( TBool aMode );
/**
* set max message size
* @param sSize
*/
void SetMaxMessageSize( TUint aSize );
/**
* stop recording/playing
*/
void Stop();
/**
* Starts remove timer. Cancels running remove timer.
* If SVK event occurs, the timer is cancelled and restarted.
*/
void StartRemoveTimerL( );
/**
* Cancels remove timer.
* If SVK event occurs, the timer is restarted.
*/
void CancelRemoveTimer( );
/**
* From MAknNaviDecoratorObserver
* Handles the navi decorator events.
* These are created by pressing the arrows related on volumebar.
*/
void HandleNaviDecoratorEventL( TInt aEventID );
/**
* From MCoeControlObserver
* Handles the control events coming from the volumebar.
* These events do not include the arrow-presses.
*/
void HandleControlEventL( CCoeControl* aControl, TCoeEvent aEventType );
/**
* Sets the observer for the volumecontrol
*/
void SetVolCtrlObserver( MCoeControlObserver& aObserver );
protected: // New functions
/**
* Constructor.
*/
void ConstructL( const RFile& aFile, TInt aVolume ,
TBool aSpeakerEarpiece, TBool aRecorder);
protected: // from MAmsRecObserver
/**
* Called to notify a change in the observed subject's state.
*/
void PlayingStops();
void UpdateL( TTimeIntervalMicroSeconds aCurrentDuration, TInt aErrorCode );
private:
/**
* Calls respective observer function
*/
void DoChangeVolumeL( );
/**
* ChangeVolume is the callback function called from change volume timer.
*/
static TInt ChangeVolume(TAny* aThis);
/**
* From CAknProgressDialog
* keyevents
*/
TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
//from MRemConCoreApiTargertObserver
protected:
/**
* @see MRemConCoreApiTargetObserver.
*
* A command has been received.
* @param aOperationId The operation ID of the command.
* @param aButtonAct The button action associated with the command.
*/
void MrccatoCommand( TRemConCoreApiOperationId aOperationId,
TRemConCoreApiButtonAction aButtonAct );
// from CAknProgressDialog
protected:
/**
* From CAknProgressDialog
* @see CAknProgressDialog for more information
*/
void PreLayoutDynInitL();
/**
* From CAknProgressDialog
* @see CAknProgressDialog for more information
*/
void PostLayoutDynInitL();
/**
* From CAknProgressDialog
* @see CAknProgressDialog for more information
*/
TBool OkToExitL(TInt aButtonId);
private: // Functions from base classes
/**
* Called by Update
* updates the progress bar texts
* @return void
* @param text and interval
*/
void UpdateProgressTextL( TInt aText,
TTimeIntervalMicroSeconds aMicroSec );
/**
* Called by Update
* updates the progress bar
* @return void
* @param currrent value of timer
*/
void DoTickL(TTimeIntervalMicroSeconds aCurrValue);
/**
* pause recording
*/
void PauseL();
/**
* continue recording.
*/
void ContinueL();
/**
* set softkeys dynamically
* @param resouce
*/
void SetSoftkeys( TInt aSk );
/**
* set icon for progressdialog
*/
void SetProgressIconL( TInt aIconId, TInt aIconMask );
/**
* change outputouting
*/
void ToLoudspeaker();
/**
* change outputouting
*/
void ToEarpiece();
/**
* sets navipanel volume indicator via appui
*/
void SetNaviVolL();
/**
* show note when max rec time appears
*/
void ShowInformationNoteL( TInt aResourceID, TBool aWaiting );
private: //data
CAudioMessageDocument& iDocument;
/**
* Observer to notify about a event.
* Not owned.
**/
MAmsVolumeObserver* iNaviVolObserver;
CEikProgressInfo* iProgressInfo;
/**
* recorder.
* Owned.
**/
CAudioMessageRecorder* iRecorder;
TTimeIntervalMicroSeconds iPausePosMicroSec;
/**
* max rec/play time.
*/
TTimeIntervalMicroSeconds iMaxDurationMicroSec;
/**
* max size, sets by appui
*/
TUint iMaxMessageSize;
/**
* for storing current volume level
**/
TInt iCurrentVolume;
TInt iTickCount;
CAknVolumePopup* iVolumePopup;
/**
* max rec/play value.
*/
TInt iFinalValue;
TInt iIncrement;
/**
* Remote Controller.
* Owned.
*/
CRemConInterfaceSelector* iInterfaceSelector;
/**
* Remote Controller.
* Not owned.
*/
CRemConCoreApiTarget* iCoreTarget;
CPeriodic* iVolumeTimer;
/**
* for volume up/down use
**/
TInt iChange;
/**
* for mode, exits, outputrouting, feature
**/
TInt iFlags;
HBufC* iTimeDuratBase;
HBufC* iTextRecording;
HBufC* iTextPlaying;
HBufC* iTextPaused;
//Following are made to reduce allocation in every 1 second when
//the progressbar is running
HBufC* iLengthMax;
HBufC* iLengthNow;
#ifdef RD_SCALABLE_UI_V2
MCoeControlObserver* iVolCtrlObserver;
#endif
};
#endif // AudioMessagePROGRESSDIALOG_H
// End of File
|
3a0719a4afff03bfdf2b5dc4cf30dcc24a6eec29 | ffdc77394c5b5532b243cf3c33bd584cbdc65cb7 | /mindspore/lite/src/litert/kernel/cpu/fp32_grad/adam.cc | 7f96e40eb448473a3a6f4a57f2037d998258890d | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | permissive | mindspore-ai/mindspore | ca7d5bb51a3451c2705ff2e583a740589d80393b | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | refs/heads/master | 2023-07-29T09:17:11.051569 | 2023-07-17T13:14:15 | 2023-07-17T13:14:15 | 239,714,835 | 4,178 | 768 | Apache-2.0 | 2023-07-26T22:31:11 | 2020-02-11T08:43:48 | C++ | UTF-8 | C++ | false | false | 6,459 | cc | adam.cc | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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 "src/litert/kernel/cpu/fp32_grad/adam.h"
#include <cmath>
#include <string>
#include "schema/model_generated.h"
#include "src/litert/kernel_registry.h"
#include "include/errorcode.h"
#include "nnacl/fp32/adam_fp32.h"
#include "plugin/device/cpu/kernel/nnacl/op_base.h"
using mindspore::kernel::KERNEL_ARCH;
using mindspore::lite::KernelRegistrar;
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
using mindspore::schema::PrimitiveType_Adam;
namespace mindspore::kernel {
constexpr static int kBeta1PowerIdx = 3;
constexpr static int kBeta2PowerIdx = 4;
constexpr static int kBeta1Idx = 6;
constexpr static int kBeta2Idx = 7;
constexpr static int kEpsilonIdx = 8;
constexpr static int kGradientIdx = 9;
int AdamCPUKernel::ReSize() { return RET_OK; }
int AdamCPUKernel::DoExecute(int task_id) {
CHECK_LESS_RETURN(in_tensors_.size(), DIMENSION_10D);
auto weight = reinterpret_cast<float *>(in_tensors_.at(kWeightIdx)->MutableData());
auto m = reinterpret_cast<float *>(in_tensors_.at(kMomentVector1stIdx)->MutableData());
auto v = reinterpret_cast<float *>(in_tensors_.at(kMomentVector2stIdx)->MutableData());
auto beta1_power = reinterpret_cast<float *>(in_tensors_.at(kBeta1PowerIdx)->MutableData());
auto beta2_power = reinterpret_cast<float *>(in_tensors_.at(kBeta2PowerIdx)->MutableData());
auto learning_rate = lr_;
auto beta1 = reinterpret_cast<float *>(in_tensors_.at(kBeta1Idx)->MutableData())[0];
auto beta2 = reinterpret_cast<float *>(in_tensors_.at(kBeta2Idx)->MutableData())[0];
auto eps = reinterpret_cast<float *>(in_tensors_.at(kEpsilonIdx)->MutableData())[0];
auto gradient = reinterpret_cast<float *>(in_tensors_.at(kGradientIdx)->MutableData());
int length = in_tensors_.at(kWeightIdx)->ElementsNum();
CHECK_NULL_RETURN(weight);
CHECK_NULL_RETURN(m);
CHECK_NULL_RETURN(v);
CHECK_NULL_RETURN(gradient);
int stride = UP_DIV(length, thread_count_);
int count = MSMIN(stride, length - stride * task_id);
int start = stride * task_id;
int end = start + count;
return DoAdam(m, v, gradient, weight, beta1, beta2, beta1_power, beta2_power, eps, learning_rate,
adam_param_->use_nesterov_, start, end);
}
int AdamRun(void *cdata, int task_id, float lhs_scale, float rhs_scale) {
auto adam_kernel = reinterpret_cast<AdamCPUKernel *>(cdata);
CHECK_NULL_RETURN(adam_kernel);
auto error_code = RET_OK;
if (adam_kernel->get_optimizer_mode() == WeightUpdateMode::VIRTUAL_BATCH) {
error_code = adam_kernel->ExecuteVirtualBatch(task_id);
} else if (adam_kernel->get_optimizer_mode() == WeightUpdateMode::ACCUMULATE_GRADS) {
error_code = adam_kernel->ExecuteVirtualBatch(task_id);
} else {
error_code = adam_kernel->DoExecute(task_id);
}
if (error_code != RET_OK) {
MS_LOG(ERROR) << "Adam run error task_id[" << task_id << "] error_code[" << error_code << "]";
return RET_ERROR;
}
return RET_OK;
}
int AdamCPUKernel::Run() {
int error_code = ParallelLaunch(this->ms_context_, AdamRun, this, thread_count_);
if (error_code != RET_OK) {
MS_LOG(ERROR) << "Adam function error error_code[" << error_code << "]";
return RET_ERROR;
}
return RET_OK;
}
int AdamCPUKernel::Prepare() {
CHECK_NULL_RETURN(adam_param_);
auto ret = OptimizerKernel::Prepare();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Failed to initialize Adam Kernel";
return RET_ERROR;
}
return RET_OK;
}
std::vector<int> AdamCPUKernel::GetOptimizerParamsIdxs() const {
std::vector<int> indices = {6, 7, 3, 4, 8};
return indices;
}
std::vector<int> AdamCPUKernel::GetTrainableParamsIdxs() const {
std::vector<int> indices = {0, 1, 2, 3, 4, 5};
return indices;
}
int AdamCPUKernel::OptimizerStep() {
CHECK_LESS_RETURN(in_tensors_.size(), DIMENSION_10D - 1);
auto weight = reinterpret_cast<float *>(in_tensors_.at(kWeightIdx)->MutableData());
auto m = reinterpret_cast<float *>(in_tensors_.at(kMomentVector1stIdx)->MutableData());
auto v = reinterpret_cast<float *>(in_tensors_.at(kMomentVector2stIdx)->MutableData());
auto beta1_power = reinterpret_cast<float *>(in_tensors_.at(kBeta1PowerIdx)->MutableData());
auto beta2_power = reinterpret_cast<float *>(in_tensors_.at(kBeta2PowerIdx)->MutableData());
auto learning_rate = lr_;
auto beta1 = reinterpret_cast<float *>(in_tensors_.at(kBeta1Idx)->MutableData())[0];
auto beta2 = reinterpret_cast<float *>(in_tensors_.at(kBeta2Idx)->MutableData())[0];
auto eps = reinterpret_cast<float *>(in_tensors_.at(kEpsilonIdx)->MutableData())[0];
size_t length = in_tensors_.at(kWeightIdx)->ElementsNum();
CHECK_NULL_RETURN(weight);
CHECK_NULL_RETURN(m);
CHECK_NULL_RETURN(v);
int ret = RET_OK;
if (grad_sum_ != nullptr && valid_grad_sum_) {
size_t start = 0;
size_t end = length;
ret = DoAdam(m, v, grad_sum_, weight, beta1, beta2, beta1_power, beta2_power, eps, learning_rate,
adam_param_->use_nesterov_, start, end);
std::fill(grad_sum_, grad_sum_ + length, 0);
OptimizerKernel::OptimizerStep();
}
return ret;
}
kernel::LiteKernel *CpuAdamFp32KernelCreator(const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, OpParameter *opParameter,
const lite::InnerContext *ctx, const kernel::KernelKey &desc) {
MS_CHECK_TRUE_MSG(opParameter != nullptr, nullptr, "Op parameter is nullptr.");
MS_ASSERT(desc.type == schema::PrimitiveType_Adam);
auto *kernel = new (std::nothrow) AdamCPUKernel(opParameter, inputs, outputs, ctx);
if (kernel == nullptr) {
MS_LOG(ERROR) << "new AdamCPUKernel fail!";
free(opParameter);
return nullptr;
}
return kernel;
}
REG_KERNEL(kCPU, kNumberTypeFloat32, PrimitiveType_Adam, CpuAdamFp32KernelCreator)
} // namespace mindspore::kernel
|
3ef29bcad0df740388cad71ae2568881712f3f6b | 0a33bbe63f007e60b798f9a7ed719b8b46419d2b | /codeforces/prac/factorialMultiplicacion.cpp | c0e931ddf31eb33b3c56b8c05708d76de6d61f92 | [] | no_license | AlvinJ15/CompetitiveProgramming | 78bb19ad0d1578badf4993a2126e6a5dac53c8b9 | 91de0a45ae10e2e84eca854d2e24f8aef769de87 | refs/heads/master | 2023-03-18T10:53:28.235212 | 2021-03-13T17:00:52 | 2021-03-13T17:00:52 | 347,413,955 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | factorialMultiplicacion.cpp | #include <bits/stdc++.h>
using namespace std;
map<long long,int> mapa;
vector<long long> factoriales;
bool esFactor(long long numero){
bool var=false;
//printf("%d\n",mapa[numero]);
if(!mapa[numero]){
if(numero==1){
mapa[numero]=1;
return true;
}
if(numero%2!=0){
mapa[numero]=-1;
return false;
}
for(int i=0;i<factoriales.size() && !var && factoriales[i]<=numero;i++){
if(numero%factoriales[i]==0){
var=var||esFactor(numero/factoriales[i]);
}
}
if(var){
mapa[numero]=1;
}
else
mapa[numero]=-1;
return var;
}
else{
if(mapa[numero]==1)
return true;
else
return false;
}
}
main(){
int n;
int resp=0;
long long numero;
factoriales.push_back(2);
for(int i=3;i<20;i++){
factoriales.push_back(factoriales[i-3]*i);
}
for(int i=0;i<factoriales.size();i++)
printf("%lld\n",factoriales[i]);
scanf("%d",&n);
while(n--){
scanf("%lld",&numero);
//mapa.clear();
printf(esFactor(numero)?"YES\n":"NO\n");
}
long long a = pow(2,62);
printf("%lld",a);
} |
2965c2bf792a84f92babd527e7ce85d406d91699 | f8cf01147e47e65c1264f4b4aedaf4cfd597b170 | /NIM/Files.h | 57a5dc044f424fca719fd04a4a4de662b04b1bd3 | [
"MIT"
] | permissive | MuhamedAbdalla/Nim | 41dfca45d1ff9ff43054a125835c38c914a7dc8d | b556a9244d8b8d11e6c2125975b66bb92e12afd1 | refs/heads/main | 2023-01-05T14:18:25.992984 | 2020-11-01T13:54:07 | 2020-11-01T13:54:07 | 300,362,374 | 1 | 1 | MIT | 2020-10-01T18:20:39 | 2020-10-01T17:20:21 | C++ | UTF-8 | C++ | false | false | 2,396 | h | Files.h | #include <iostream>
#include <algorithm>
#include <string>
#include <math.h>
#include <conio.h>
#include <fstream>
#include <Windows.h>
#include <mmsystem.h>
using namespace std;
void Nim_Game() { // view the name of game
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 10;
string nim_data;
ifstream file;
file.open("Data\\nim.txt");
while (!file.eof()) {
getline(file, nim_data);
if (nim_data.find("_") != -1) {
i += 2;
}
SetConsoleTextAttribute(h, i);
cout << nim_data << endl;
}
}
void menu() { //view the menu of the game
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 14;
string nim_data;
fstream file;
file.open("Data\\menu.txt");
while (!file.eof()) {
getline(file, nim_data);
SetConsoleTextAttribute(h, i);
cout << nim_data << endl;
}
}
void Instructions() { // give information about(nim game)
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 11;
string nim_data;
fstream file;
file.open("Data\\instructions.txt");
while (!file.eof()) {
getline(file, nim_data);
SetConsoleTextAttribute(h, i);
cout << nim_data << endl;
}
char back;
back = _getch();
}
void Credits() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 8;
string nim_data;
fstream file;
file.open("Data\\credits.txt");
while (!file.eof()) {
getline(file, nim_data);
SetConsoleTextAttribute(h, i);
cout << nim_data << endl;
}
char back;
back = _getch();
}
void Choose_Version() {// choose a version you want to paly
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 13;
string nim_data;
fstream file;
file.open("Data\\version.txt");
while (!file.eof()) {
getline(file, nim_data);
SetConsoleTextAttribute(h, i);
cout << nim_data << endl;
}
}
void Draw_Score() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 10, con = 1;
string nim_data;
fstream file;
file.open("ScoreBoard.txt");
while (!file.eof()) {
getline(file, nim_data);
SetConsoleTextAttribute(h, i);
cout << "\t\t\t\t\t\t\t\t" << con++ << "-" << nim_data << endl;
}
cout << endl << "\t\t\t\t\t\t\t\t\t " << "press any key to go back." << endl;
char back;
back = _getch();
}
void End_Game() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 6;
string nim_data;
fstream file;
file.open("Data\\end.txt");
while (!file.eof()) {
getline(file, nim_data);
SetConsoleTextAttribute(h, i);
cout << nim_data << endl;
}
}
|
0ce6b5e13ad30bedf17ff9089414155fe4014774 | 657df365d5afd496d62d0567fb22b4e5ce79f493 | /Classes/LevelPauseMenu.h | bc0b37e598b5b3879841f5fe3d0b68527bf6cebd | [] | no_license | aismann/impossiblebricks | 946702e3a4e88768ef8056b28a383d85d9a81a5d | d770fe60f72b77554b55fe589f80692be0411dcf | refs/heads/master | 2023-03-15T17:49:29.238875 | 2016-05-26T19:37:27 | 2016-05-26T19:37:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | h | LevelPauseMenu.h | #ifndef _LEVEL_PAUSE_MENU_H_
#define _LEVEL_PAUSE_MENU_H_
#include "cocos2d.h"
#include "ui/CocosGUI.h"
class LevelPauseMenu : public cocos2d::Layer
{
public:
static LevelPauseMenu *create();
void retryLevel(Ref *pSender, cocos2d::ui::TouchEventType type);
void levelSelect(Ref *pSender, cocos2d::ui::TouchEventType type);
void continueLevel(Ref *pSender, cocos2d::ui::TouchEventType type);
protected:
LevelPauseMenu();
~LevelPauseMenu();
virtual bool init() override;
};
#endif //end _LEVEL_PAUSE_MENU_H_ |
958f360fc8d64bc4ef2be74b1ded7fbe2d6f5a75 | fa538581ecd8e002c589e85f1cf04749390951be | /Molecular_VIS/src/Camera/Camera.cpp | 1f84fb586e6343a83c1bc8c71a30f5c5e65acfac | [] | no_license | linkhack/Molecular_VIS | 5c2df5101ca2a1e1554f7cee452514bd320a4874 | d4c5f6749e21d8d0323c2016f940fd65bcf01b40 | refs/heads/master | 2020-04-28T10:15:42.228922 | 2019-06-10T18:58:09 | 2019-06-10T18:58:09 | 175,195,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,411 | cpp | Camera.cpp | #include "Camera.h"
using namespace glm;
/*
Creates Camera, fov in degrees
*/
Camera::Camera(float fov, float aspect, float near, float far)
{
pitch = 0.0f;
yaw = 0.0f;
radius = 1.0f;
position = vec3(0.0f, 0.0f, 20.0f);
strafe = vec3(0.0f, 0.0f, 0.0f);
vec3 up = vec3(0.0f, 1.0f, 0.0f);
vec3 right = vec3(1.0f, 0.0f, 0.0f);
projectionMatrix = perspective(radians(fov), aspect, near, far);
mat4 rotation = rotate(mat4(1.0f), pitch, right)*rotate(mat4(1.0f), -yaw, up);
viewMatrix = transpose(rotation) * translate(mat4(1.0f), -position);
projectionViewMatrix = projectionMatrix * viewMatrix;
inverseProjectionViewMatrix = glm::inverse(projectionViewMatrix);
}
Camera::~Camera()
{
}
glm::mat4 Camera::getInverseProjectionViewMatrix()
{
return inverseProjectionViewMatrix;
}
mat4 Camera::getProjectionViewMatrix()
{
return projectionViewMatrix;
}
glm::mat4 Camera::getViewMatrix()
{
return viewMatrix;
}
glm::vec3 Camera::getPosition()
{
return position;
}
glm::vec3 Camera::getDirection()
{
return normalizedDirection;
}
void Camera::update(int x, int y, float zoom, bool dragging, bool strafing)
{
mat4 rotation = mat4(1.0f);
radius = zoom;
if (radius < 0.2) radius = 0.2f;
int deltaX = x - lastX;
int deltaY = y - lastY;
if (dragging)
{
float deltaAnglePitch = 2 * pi<float>()*float(deltaY) / 600.0f;
float deltaAngleYaw = pi<float>()*float(deltaX) / 600.0f;
pitch += deltaAnglePitch;
yaw -= deltaAngleYaw;
if (pitch < -pi<float>() / 2.0f + 0.01f)
{
pitch = -pi<float>() / 2.0f + 0.01f;
}
if (pitch > pi<float>() / 2.0f - 0.01f)
{
pitch = pi<float>() / 2.0f - 0.01f;
}
}
position = radius * vec3(cosf(pitch)*sin(yaw), sinf(pitch), cosf(pitch)*cosf(yaw));
vec3 up = vec3(0.0f, 1.0f, 0.0f);
vec3 lookingDirection =-position;
normalizedDirection = glm::normalize(lookingDirection);
vec3 front = normalize(lookingDirection);
vec3 right = normalize(cross(front, up));
vec3 zAxis = cross(right, front);
if (strafing)
{
strafe += -0.01f * float(deltaX) * right + 0.01f * float(deltaY) * zAxis;
}
position += strafe;
rotation = mat4(vec4(right, 0.0f), vec4(zAxis, 0.0f), vec4(-front, 0.0f), vec4(0.0f, 0.0f, 0.0f, 1.0f));
viewMatrix = transpose(rotation)*translate(mat4(1.0f),-position);
projectionViewMatrix = projectionMatrix*viewMatrix;
inverseProjectionViewMatrix = glm::inverse(projectionViewMatrix);
lastX = x;
lastY = y;
} |
14b0fb95e2d10a7a3229d2494c2abc0bba1747d1 | 133e289bebeab00cd9acdcb377d26ed2488907e6 | /XEngine/XEngine/XEngine.cpp | 38de04f23d1970a10fd9f8fd8e654654a3e39e7b | [] | no_license | DoYouEven/XEngine | 2e93defce77b7875b53640c04a77ad8cbf98bd8d | 6fb2f8793a7e3641b0b69d3cf9addb46fb47226e | refs/heads/master | 2021-01-21T12:10:57.771810 | 2015-02-19T18:29:17 | 2015-02-19T18:29:17 | 31,029,703 | 3 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,720 | cpp | XEngine.cpp | #include "XEngine.h"
XEngine::XEngine()
{
}
XEngine::~XEngine()
{
}
GLvoid XEngine::UnInit()
{
delete XEngine::getXEngine();
}
XEngine *XEngine::getXEngine()
{
static XEngine *e = new XEngine();
return e;
}
GLvoid XEngine::establishProjecttionMatrix(GLsizei width, GLsizei height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.01f, 1000.00f);
}
GLvoid XEngine::initGL(GLsizei width, GLsizei height)
{
establishProjecttionMatrix(width, height);
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_PERSPECTIVE_CORRECTION_HINT);
}
void XEngine::Init(GLint windowWidth, GLint windowHeight)
{
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8);
Uint32 flags = SDL_SWSURFACE;
//SDL_Surface *screen = SDL_SetVideoMode(windowWidth, windowHeight, 32, flags);
//flags = screen->flags;
//screen = SDL_SetVideoMode(0, 0, 0, screen->flags ^ SDL_FULLSCREEN);
// screen = SDL_SetVideoMode(0, 0, 0, flags);
SDL_SetVideoMode(windowWidth, windowHeight, 0, SDL_OPENGL);
initGL(windowWidth, windowHeight);
SDL_EnableUNICODE(1);
Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);
Light::Init();
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initilalize GLEW!" << std::endl;
exit(-1);
}
if (!glewIsSupported("GL_ARB_multitexture "
"GL_ARB_texture_env_combine "
"GL_ARB_vertex_buffer_object "
))
{
std::cout << "Required OpenGL extension support is missing." << std::endl;
exit(-1);
}
}
|
58af5a88730a842bdfcde04bea8a6b98db95c4ba | 9c734b3df7817b6909110b51c164363732f6acb2 | /Accelerometer.cpp | 5e43b901564e339a305dce28649f6ce2515315f4 | [] | no_license | brnd-from-mars/AVR_Periph | 69e1b2c7e47a877de5b4dc30d60ba0fd02964497 | a7b654bbc26ed56598476416c832e6f3d9ff7f5c | refs/heads/master | 2021-11-04T12:09:37.345362 | 2019-04-27T23:26:14 | 2019-04-27T23:26:14 | 182,405,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,708 | cpp | Accelerometer.cpp | //
// Created by Brendan Berg on 2019-04-21.
//
#include <periph/Accelerometer.hpp>
#include <math.h>
Accelerometer::Accelerometer (AnalogInputController& analogInputController)
: m_AnalogInputController(analogInputController), m_RegisteredPins(0),
m_Sensitivity(0x12), m_Bias(0x54)
{ }
void Accelerometer::RegisterAxis (uint8_t channel, int16_t initialAccel)
{
m_Pins[m_RegisteredPins] = AnalogInputPin(channel, 0x10);
m_InitialAcceleration[m_RegisteredPins] = initialAccel;
m_AnalogInputController.RegisterAnalogPin(&m_Pins[m_RegisteredPins]);
++m_RegisteredPins;
}
void Accelerometer::Calibrate ()
{
for (uint8_t i = 0; i < m_RegisteredPins; ++i)
{
m_InitialRawValue[i] = m_Pins[i].GetValue();
}
int16_t sensitivity = 0x0000;
uint8_t sensitivityValues = 0x00;
for (uint8_t i = 0; i < m_RegisteredPins; ++i)
{
for (uint8_t j = (i + 1); j < m_RegisteredPins; ++j)
{
if (CalculateSensitivity(i, j, sensitivity))
{
++sensitivityValues;
}
}
}
sensitivity = sensitivity / sensitivityValues;
m_Sensitivity = sensitivity;
int16_t bias = 0x0000;
for (uint8_t i = 0; i < m_RegisteredPins; ++i)
{
bias += m_InitialRawValue[i] - static_cast<uint16_t>(
sensitivity * m_InitialAcceleration[i] / 0xff);
}
bias = bias / m_RegisteredPins;
m_Bias = bias;
}
int16_t Accelerometer::GetAcceleration (uint8_t axis)
{
auto offset = m_Pins[axis].GetValue() - m_Bias;
return 0xff * offset / m_Sensitivity;
}
double Accelerometer::GetFloatAcceleration (uint8_t axis)
{
return static_cast<double>(GetAcceleration(axis)) /
static_cast<double>(0xff);
}
int8_t Accelerometer::GetClimbAngle (uint8_t downAxis, uint8_t fwdAxis)
{
double total = sqrt(square(GetFloatAcceleration(downAxis)) +
square(GetFloatAcceleration(fwdAxis)));
double accelDown = GetFloatAcceleration(downAxis) / total;
double accelFwd = GetFloatAcceleration(fwdAxis) / total;
accelDown = fmin(accelDown, 1.0);
double falpha = acos(accelDown) / M_1_PI;
auto alpha = static_cast<int8_t>(0x7f * falpha) * ((accelFwd < 0) ? -1 : 1);
return alpha;
}
bool Accelerometer::CalculateSensitivity (uint8_t axis1, uint8_t axis2,
int16_t& sensitivity)
{
if (m_InitialAcceleration[axis1] == m_InitialAcceleration[axis2])
{
return false;
}
auto dRaw = m_InitialRawValue[axis1] - m_InitialRawValue[axis2];
auto dAccel = m_InitialAcceleration[axis1] - m_InitialAcceleration[axis2];
sensitivity += 0xff * dRaw / dAccel;
return true;
}
|
853692534b1195ffda9b3e633e9eae2f44a59ab7 | 6a89bf19bc87424045d931b782ef8102dc5dc610 | /modules/meta/include/shard/meta/type_traits.hpp | b1090a9ab76f57e727f9bc7d57d7bd8cd31205c5 | [
"MIT"
] | permissive | ikimol/shard | 0cbf35eb2ad32a828f02d09462c525edf96d4113 | 6f653655a349ccac228e8255f6abcc10435816e1 | refs/heads/master | 2023-08-30T22:49:43.501779 | 2023-03-07T17:35:38 | 2023-03-07T17:35:38 | 167,057,756 | 0 | 0 | MIT | 2020-02-28T12:17:00 | 2019-01-22T19:54:01 | C++ | UTF-8 | C++ | false | false | 5,648 | hpp | type_traits.hpp | // Copyright (c) 2023 Miklos Molnar. All rights reserved.
#pragma once
#include <tuple>
#include <type_traits>
namespace shard {
namespace meta {
namespace detail {
// clang-format off
template <typename T> struct is_integer_impl : std::false_type {};
// signed
template <> struct is_integer_impl<char> : std::true_type {};
template <> struct is_integer_impl<short> : std::true_type {};
template <> struct is_integer_impl<int> : std::true_type {};
template <> struct is_integer_impl<long> : std::true_type {};
template <> struct is_integer_impl<long long> : std::true_type {};
// unsigned
template <> struct is_integer_impl<unsigned char> : std::true_type {};
template <> struct is_integer_impl<unsigned short> : std::true_type {};
template <> struct is_integer_impl<unsigned int> : std::true_type {};
template <> struct is_integer_impl<unsigned long> : std::true_type {};
template <> struct is_integer_impl<unsigned long long> : std::true_type {};
// clang-format on
template <typename S, typename T>
class is_streamable_impl {
private:
template <typename S1, typename T1>
static auto test(int) -> decltype(std::declval<S1&>() << std::declval<T1>(), std::true_type());
template <typename, typename>
static auto test(...) -> std::false_type;
public:
static const bool value = decltype(test<S, T>(0))::value;
};
template <typename T>
class has_begin_end_impl {
private:
template <typename U = std::decay_t<T>,
typename B = decltype(std::declval<U&>().begin()),
typename E = decltype(std::declval<U&>().end())>
static std::true_type test(int);
template <typename...>
static auto test(...) -> std::false_type;
public:
static const bool value = decltype(test<T>(0))::value;
};
template <typename T>
class has_key_value_pair_impl {
private:
template <typename U = std::decay_t<T>,
typename V = typename U::value_type,
typename F = decltype(std::declval<V&>().first),
typename S = decltype(std::declval<V&>().second)>
static std::true_type test(int);
template <typename...>
static auto test(...) -> std::false_type;
public:
static const bool value = decltype(test<T>(0))::value;
};
} // namespace detail
// is_<type> structs
template <typename T>
struct is_integer : detail::is_integer_impl<std::remove_cv_t<T>> {};
template <typename T>
struct is_bool : std::is_same<std::remove_cv_t<T>, bool> {};
template <typename T>
struct is_numeric : std::bool_constant<is_integer<T>::value || std::is_floating_point<T>::value> {};
template <typename S, typename T>
struct is_streamable : std::bool_constant<detail::is_streamable_impl<S, T>::value> {};
template <typename T>
struct has_begin_end : std::bool_constant<detail::has_begin_end_impl<T>::value> {};
template <typename T>
struct has_key_value_pair : std::bool_constant<detail::has_key_value_pair_impl<T>::value> {};
// is_empty
template <typename... Args>
struct is_empty : std::bool_constant<sizeof...(Args) == 0> {};
// are_same
template <typename T, typename...>
struct are_same : std::true_type {};
template <typename T, typename U, typename... Args>
struct are_same<T, U, Args...> : std::bool_constant<std::is_same<T, U>::value && are_same<T, Args...>::value> {};
// operators
template <typename T>
using not_type = std::bool_constant<!T::value>;
template <typename Condition, typename Then, typename Else>
using if_type = std::conditional_t<Condition::value, Then, Else>;
template <typename... Args>
struct and_type : std::bool_constant<true> {};
template <typename T, typename... Args>
struct and_type<T, Args...> : if_type<T, and_type<Args...>, std::bool_constant<false>> {};
template <typename... Args>
struct or_type : std::bool_constant<false> {};
template <typename T, typename... Args>
struct or_type<T, Args...> : if_type<T, std::bool_constant<true>, or_type<Args...>> {};
template <typename... Args>
using enable_if_all_t = std::enable_if_t<and_type<Args...>::value, int>;
template <typename... Args>
using enable_if_any_t = std::enable_if_t<or_type<Args...>::value, int>;
// disable_if
// clang-format off
template <bool, typename T = void> struct disable_if {};
template <typename T> struct disable_if<false, T> { using type = T; };
// clang-format on
template <bool Bool, typename T = void>
using disable_if_t = typename disable_if<Bool, T>::type;
// function traits
// clang-format off
template <typename> struct result_of;
template <class R, class... Args> struct result_of<R(Args...)> { using type = R; };
template <typename R, typename... Args> struct result_of<R(*)(Args...)> { using type = R; };
// clang-format on
template <typename T>
struct functor_traits : public functor_traits<decltype(&T::operator())> {};
template <typename T, typename R, typename... Args>
struct functor_traits<R (T::*)(Args...) const> {
static constexpr auto arity = sizeof...(Args);
typedef R result_type;
using args_type = std::tuple<Args...>;
template <std::size_t N>
using arg_type = typename std::tuple_element<N, args_type>::type;
};
template <typename T>
using result_of_t = typename result_of<T>::type;
} // namespace meta
using meta::is_bool;
using meta::is_integer;
using meta::is_numeric;
using meta::is_streamable;
using meta::has_begin_end;
using meta::has_key_value_pair;
using meta::are_same;
using meta::is_empty;
using meta::and_type;
using meta::if_type;
using meta::not_type;
using meta::or_type;
using meta::enable_if_all_t;
using meta::enable_if_any_t;
using meta::disable_if;
using meta::disable_if_t;
using meta::functor_traits;
using meta::result_of_t;
} // namespace shard
|
213ee442b3b20c435e3bc52bbb15609ebef68088 | 42f422c82e8e9020800e397e242d445f6d8a8f4c | /NavigateParking/parkmapgridinfo.cpp | 88aa4fec4ba469f765378217932a7451ebc7d186 | [] | no_license | liukai-tech/NavigateParking | 85ae70b79c31d8eeec5a12f20094c1da02363d6e | 0e3bb4b61855544b56ef29ab898c7a94d260f9c5 | refs/heads/master | 2022-03-07T12:35:37.526812 | 2019-11-10T10:39:10 | 2019-11-10T10:39:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,584 | cpp | parkmapgridinfo.cpp | #include "parkmapgridinfo.h"
#include "parkingpositioninfo.h"
#include <QJsonObject>
#include <QJsonArray>
QSharedPointer<ParkMapGridInfo> ParkMapGridInfo::m_Ins;
ParkMapGridInfo* ParkMapGridInfo::GetIns()
{
if (nullptr == m_Ins.get()){
m_Ins.reset(new ParkMapGridInfo());
}
return m_Ins.get();
}
ParkMapGridInfo::ParkMapGridInfo()
{
}
ParkMapGridInfo::~ParkMapGridInfo()
{
}
void ParkMapGridInfo::Write(QJsonObject &json) const
{
QJsonArray gridArray;
QJsonArray gridToRoadArray;
QJsonArray gridToParkingPositionArray;
for(int i = 0; i < MAP_WIDTH * MAP_HEIGHT; ++i){
gridArray.append(m_Map[i]);
gridToRoadArray.append(m_GridToRoad[i]);
gridToParkingPositionArray.append(m_GridToParkingPosition[i]);
}
json["grids"] = gridArray;
json["gridToRoad"] = gridToRoadArray;
json["gridToParkingPosition"] = gridToParkingPositionArray;
}
void ParkMapGridInfo::Read(const QJsonObject &json)
{
QJsonArray gridsArray;
QJsonArray gridToRoadArray;
QJsonArray gridToParkingPositionArray;
if (json.contains("grids") && json["grids"].isArray()){
gridsArray = json["grids"].toArray();
}
if (json.contains("gridToRoad") && json["gridToRoad"].isArray()){
gridToRoadArray = json["gridToRoad"].toArray();
}
if (json.contains("gridToParkingPosition") && json["gridToParkingPosition"].isArray()){
gridToParkingPositionArray = json["gridToParkingPosition"].toArray();
}
for(int i = 0; i < MAP_WIDTH * MAP_HEIGHT; ++i){
if(i < gridsArray.size()){
m_Map[i] = static_cast<MapGrid>(gridsArray[i].toInt());
}
if(i < gridToRoadArray.size()){
m_GridToRoad[i] = gridToRoadArray[i].toInt();
}
if(i < gridToParkingPositionArray.size()){
m_GridToParkingPosition[i] = gridToParkingPositionArray[i].toInt();
}
}
}
void ParkMapGridInfo::Initialize()
{
// default value
for(int i = 0; i < MAP_WIDTH; ++i){
for(int j = 0; j < MAP_HEIGHT; ++j){
int index = MAP_WIDTH * j + i;
m_GridToRoad[index] = 0;
m_GridToParkingPosition[index] = 0;
if(i == 0 || j == 0 || i == MAP_WIDTH - 1 || j == MAP_HEIGHT - 1){
m_Map[index] = MapGrid::MG_Wall;
continue;
}
m_Map[index] = MapGrid::MG_None;
}
}
buildLeftPart();
buildRightPart();
buildCenterHorizontal();
buildTopAndBottom();
buildVerticalRoad();
buildParkingPosition();
}
void ParkMapGridInfo::buildLeftPart()
{
// build road
for(int i = 1; i < MAP_HEIGHT - 1; ++i){
// left main
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + 6 + j;
m_Map[index] = MapGrid::MG_Road_Left;
}
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + 9 + j;
m_Map[index] = MapGrid::MG_Road_Right;
}
}
// build park position
for(int i = 1; i < MAP_HEIGHT - 1; ++i){
// left near wall
for(int j = 0; j < 5; ++j){
int index = i * MAP_WIDTH + 1 + j;
m_Map[index] = MapGrid::MG_ParkPosition;
}
// left near road
for(int j = 0; j < 10; ++j){
int index = i * MAP_WIDTH + 12 + j;
m_Map[index] = MapGrid::MG_ParkPosition;
}
}
// left part
for(int iter = 0; iter < 29; ++iter){
for(int i = 1; i < MAP_HEIGHT - 1; ++i){
// road left
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + (22 + iter * 16) + j;
m_Map[index] = MapGrid::MG_Road_Left;
}
// road right
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + (25 + iter * 16) + j;
m_Map[index] = MapGrid::MG_Road_Right;
}
// park
for(int j = 0; j < 10; ++j){
int index = i * MAP_WIDTH + (28 + iter * 16) + j;
m_Map[index] = MapGrid::MG_ParkPosition;
}
}
}
}
void ParkMapGridInfo::buildRightPart()
{
// build road
for(int i = 1; i < MAP_HEIGHT - 1; ++i){
// left main
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + (MAP_WIDTH - 9) - j;
m_Map[index] = MapGrid::MG_Road_Left;
}
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + (MAP_WIDTH - 6) - j;
m_Map[index] = MapGrid::MG_Road_Right;
}
}
// build park position
for(int i = 1; i < MAP_HEIGHT - 1; ++i){
// left near wall
for(int j = 0; j < 5; ++j){
int index = i * MAP_WIDTH + (MAP_WIDTH - 1) - j;
m_Map[index] = MapGrid::MG_ParkPosition;
}
// left near road
for(int j = 0; j < 10; ++j){
int index = i * MAP_WIDTH + (MAP_WIDTH - 12) - j;
m_Map[index] = MapGrid::MG_ParkPosition;
}
}
// left part
for(int iter = 0; iter < 29; ++iter){
for(int i = 1; i < MAP_HEIGHT - 1; ++i){
// road left
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + (MAP_WIDTH - 25 - iter * 16) - j;
m_Map[index] = MapGrid::MG_Road_Left;
}
// road right
for(int j = 0; j < 3; ++j){
int index = i * MAP_WIDTH + (MAP_WIDTH - 22 - iter * 16) - j;
m_Map[index] = MapGrid::MG_Road_Right;
}
// park
for(int j = 0; j < 10; ++j){
int index = i * MAP_WIDTH + (MAP_WIDTH - 28 - iter * 16) - j;
m_Map[index] = MapGrid::MG_ParkPosition;
}
}
}
}
void ParkMapGridInfo::buildCenterHorizontal()
{
for(int i = 1; i < MAP_HEIGHT - 1; ++i){
// left
for(int j = 0; j < 5; ++j){
int index = i * MAP_WIDTH + 486 + j;
m_Map[index] = MapGrid::MG_Road_Left;
}
// right
for(int j = 0; j < 5; ++j){
int index = i * MAP_WIDTH + 490 + j;
m_Map[index] = MapGrid::MG_Road_Right;
}
// park
for(int j = 0; j < 12; ++j){
int index = i * MAP_WIDTH + 494 + j;
m_Map[index] = MapGrid::MG_ParkPosition;
}
// left
for(int j = 0; j < 5; ++j){
int index = i * MAP_WIDTH + 506 + j;
m_Map[index] = MapGrid::MG_Road_Left;
}
// right
for(int j = 0; j < 5; ++j){
int index = i * MAP_WIDTH + 510 + j;
m_Map[index] = MapGrid::MG_Road_Right;
}
}
}
void ParkMapGridInfo::buildTopAndBottom()
{
// top
for(int i = 12; i < MAP_WIDTH - 12; ++i){
for(int j = 0; j < 5; ++j){
int index = (j + 1) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_ParkPosition;
}
}
// bottom
for(int i = 12; i < MAP_WIDTH - 12; ++i){
for(int j = 0; j < 5; ++j){
int index = (MAP_HEIGHT - j - 2) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_ParkPosition;
}
}
}
void ParkMapGridInfo::buildVerticalRoad()
{
// top
for(int i = 12; i < MAP_WIDTH - 11; ++i){
for(int j = 0; j < 3; ++j){
int index = (j + 6) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Left;
}
for(int j = 0; j < 3; ++j){
int index = (j + 9) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Right;
}
}
// bottom
for(int i = 12; i < MAP_WIDTH - 11; ++i){
for(int j = 0; j < 3; ++j){
int index = (MAP_HEIGHT - 9 - j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Left;
}
for(int j = 0; j < 3; ++j){
int index = (MAP_HEIGHT - 6 - j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Right;
}
}
// other road
for(int iter = 1; iter < 3; ++iter){
for(int i = 12; i < MAP_WIDTH - 11; ++i){
for(int j = 0; j < 3; ++j){
int index = (iter * 162 + j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Left;
}
for(int j = 0; j < 3; ++j){
int index = (iter * 162 + 3 + j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Right;
}
for(int j = 0; j < 3; ++j){
int index = (MAP_HEIGHT - iter * 162 - 3 - j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Left;
}
for(int j = 0; j < 3; ++j){
int index = (MAP_HEIGHT - iter * 162 - j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Right;
}
}
}
// center
for(int i = 12; i < MAP_WIDTH - 11; ++i){
for(int j = 0; j < 5; ++j){
int index = (MAP_WIDTH / 2 - 5 + j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Left;
}
for(int j = 0; j < 5; ++j){
int index = (MAP_WIDTH / 2 + j) * MAP_WIDTH + i;
m_Map[index] = MapGrid::MG_Road_Right;
}
}
}
void ParkMapGridInfo::buildParkingPosition()
{
// near wall parking position
for(int i = 1; i < MAP_HEIGHT - 1;){
if(i == 1 || i == 995){
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Horizontal
,i * MAP_WIDTH + 1,4,5);
i += 4;
}else{
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Horizontal
,i * MAP_WIDTH + 1,3,5);
i += 3;
}
}
for(int i = 12; i < MAP_WIDTH - 12;){
if(i == 12){
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Vertical
,i + MAP_WIDTH,5,4);
i += 4;
}else{
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Vertical
,i + MAP_WIDTH,5,3);
i += 3;
}
}
for(int i = 1; i < MAP_HEIGHT - 1;){
if(i == 1 || i == 995){
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Horizontal
,i * MAP_WIDTH + MAP_WIDTH - 5,4,5);
i += 4;
}else{
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Horizontal
,i * MAP_WIDTH + MAP_WIDTH - 5,3,5);
i += 3;
}
}
for(int i = 12; i < MAP_WIDTH - 12;){
if(i == 12){
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Vertical
,i + MAP_WIDTH * (MAP_HEIGHT - 5),5,4);
i += 4;
}else{
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Vertical
,i + MAP_WIDTH * (MAP_HEIGHT - 5),5,3);
i += 3;
}
}
// middle
int iCount = 0;
for(int i = 12; i < MAP_WIDTH - 11; ++i){
for(int j = 12; j < MAP_HEIGHT - 11; ++j){
int index = j * MAP_WIDTH + i;
if(m_Map[index] != MapGrid::MG_ParkPosition){
continue;
}
if(m_Map[(j + 2) * MAP_WIDTH + i] == MapGrid::MG_ParkPosition){
if(i == 494 || i == 500){
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Horizontal
,index,3,6);
}else{
ParkingPositions::GetIns()->AddParkingPosition(ParkingPositions::GetIns()->GenerateIndex()
,ParkingDirection::PD_Horizontal
,index,3,5);
}
}
j += 2;
}
++iCount;
if(iCount % 2 == 0){
i += 10;
}else{
i += 4;
}
// center
if(i == 496){
i = 493;
}
static bool hasCheck504 = false;
if(i == 504 && !hasCheck504){
hasCheck504 = true;
i = 499;
}
if(i == 504 && hasCheck504){
i = 514;
iCount = 0;
}
}
}
|
f4a626e8e073e2851505076959c098a91e81f791 | eff672b28acc2da80cec16a48cc70c7aaff1b787 | /GameState.hpp | 23c7464f77a1df02ae5892a61cc830497cf31247 | [] | no_license | Streq/GenericPlatformer | 6da2ccf39466d3b0d17ffe92ccb026d4c046d4db | d1dd30922e5f91ba1648dacc4b2e279a089cb6d1 | refs/heads/master | 2021-07-16T13:18:51.695272 | 2017-10-25T03:06:42 | 2017-10-25T03:06:42 | 103,204,818 | 0 | 0 | null | 2017-09-12T13:23:42 | 2017-09-12T01:05:50 | C++ | UTF-8 | C++ | false | false | 1,170 | hpp | GameState.hpp | /*
* GameState.hpp
*
* Created on: Sep 30, 2017
* Author: santiago
*/
#pragma once
#include <Mocho/Application/AppState.hpp>
#include <Mocho/Collision/collision.hpp>
#include <Mocho/definitions.hpp>
#include <Mocho/vec2.hpp>
#include <vector>
#include <SFML/Window/Keyboard.hpp>
#include "Entities/Entity.hpp"
namespace mch {
class GameState: public AppState {
public:
//Update the state
//@returns bool stating wether or not to keep updating
// for next states in the stack
virtual bool update();
//Draw the current state
virtual void draw(sf::RenderTarget& target, sf::RenderStates states)const;
//Handle a given event
//@returns bool stating wether or not to keep handling input
// for next states in the stack
virtual bool input(const sf::Event& event);
void init();
private:
float m_player_speed;
float m_player_acceleration;
std::vector<Entity> m_walls;
std::vector<Player> m_characters;
enum input_key{
up,left,down,right,size
};
using Controller = sf::Keyboard::Key [input_key::size];
Controller m_input_1;
Controller m_input_2;
private:
Vec2f getInputDirection();
};
} /* namespace mch */
|
06da7b6ced476a1639b3d10709bfdd61bc438af9 | 48d05b089416d40e1bb68e560b5d8d525a2f5c71 | /project4/Relation.h | 89a17aed28b77d64de834b2f715db763a7a7156c | [] | no_license | dpettingill/CS_236 | 49bc254cefb0110119cf37f6529b10a61aaf39b9 | 69ff8d5249f06b999bf0e01837b9a7ef5194f2f7 | refs/heads/master | 2020-09-01T21:22:55.764244 | 2019-12-11T15:36:31 | 2019-12-11T15:36:31 | 219,061,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,764 | h | Relation.h | #pragma once
#include <stdio.h>
#include <iostream>
#include<string>
#include <algorithm>
#include <sstream>
#include<set>
#include<vector>
#include "Tuple.h"
using namespace std;
class Relation
{
private:
/* data */
string my_name;
Tuple my_header;
set<Tuple> my_set;
public:
//Relation(string name, Tuple header);
Relation();
~Relation();
string toString();
void addTuple(Tuple my_tuple);
void fillRelation(Relation& r);
Relation select(int col, string val);
Relation select(int col1, int col2);
Relation project(vector<int> toProject);
Relation rename(Tuple t);
Tuple getHeader();
int getSetSize();
void setHeader(Tuple t);
void setName(string name);
set<Tuple> getSet();
Relation naturalJoin(Relation r2);
void findMatchingCols(Relation r2);
bool isJoinable(Tuple t1, Tuple t2);
Tuple combineTuples(Tuple t1, Tuple t2);
Tuple combTupCartesian(Tuple t1, Tuple t2);
Relation unionize(Relation toUnion);
};
//When you create a relation you give it a name and a header
//create a function where you can add in tuples
// relation has string name
// tuple header
// set<tuple> rows
/*for(Tuple t: mySet) {
It will perform this loop on every Tuple that is in mySet.
cout << Tuple.toString();
}*/
// Relation
// select(int col, string val) //create a new relation where the specified column has the specified value
// select(int col1, int col2) //this enforces that value at col1 is the same as the value at col2
//myNewRelation = myRelation.select(approp. params);
// project(vector<int> toProject) //r2 = r1.project(<2,0>) //this says I want col 2 and then col 0
//rename(Tuple t) //don't need to implement for this lab
|
ba1a81f94df4160da88b1012bad5c942a31922f4 | 128b5565aa8757699e5e159ef22e7534eb59e9f8 | /Utf8.h | 249ccdc8fe1e8c1a0095eff3ab0049763485e82d | [] | no_license | bvoq/JumpingParser | b97dec9586b8348269d08497bdae939281333a84 | 40773d3aa7d772522bd094e016739c5d3a078b43 | refs/heads/master | 2021-01-22T07:39:30.772812 | 2017-02-13T20:57:11 | 2017-02-13T20:57:11 | 81,841,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,361 | h | Utf8.h | //
// Utf8.h
// AggregateProver
//
// Created by kdkdk on 12.02.17.
// Copyright © 2017 a. All rights reserved.
//
#ifndef Utf8_h
#define Utf8_h
#include <iostream>
namespace utf8 {
//Modified code snippet from: http://stackoverflow.com/questions/6691555/converting-narrow-string-to-wide-string
std::wstring toWideString(std::string str) {
std::wstring str2(str.size(), L' '); // Make room for characters
// Copy string to wstring.
std::copy(str.begin(), str.end(), str2.begin());
return str2;
}
}
//UNUSED:
/*
struct utf8 {
std::string str = "";
std::wstring wstr = L"";
utf8 () {}
utf8 (std::string _str) : str(_str) {}
utf8 (std::string & _str) : str(_str) {}
//Code snippet from: http://stackoverflow.com/questions/4063146/getting-the-actual-length-of-a-utf-8-encoded-stdstring
std::size_t size() {
std::size_t len = 0;
std::string::iterator it = str.begin();
while (*it) len += (*it++ & 0xc0) != 0x80;
return len;
}
//Modificated snippet from: http://stackoverflow.com/questions/30995246/substring-of-a-stdstring-in-utf-8-c11
utf8 substr(unsigned int start, std::size_t leng)
{
if (leng==0) { return utf8(""); }
std::size_t c, i, ix, q, min = std::string::npos, max = std::string::npos;
for (q=0, i=0, ix=str.length(); i < ix; i++, q++)
{
if (q==start){ min=i; }
if (q <= start+leng || leng == std::string::npos) max=i;
c = (unsigned char) str[i];
if (
//c>=0 &&
c<=127) i+=0;
else if ((c & 0xE0) == 0xC0) i+=1;
else if ((c & 0xF0) == 0xE0) i+=2;
else if ((c & 0xF8) == 0xF0) i+=3;
//else if (($c & 0xFC) == 0xF8) i+=4; // 111110bb //byte 5, unnecessary in 4 byte UTF-8
//else if (($c & 0xFE) == 0xFC) i+=5; // 1111110b //byte 6, unnecessary in 4 byte UTF-8
else return utf8("");//invalid utf8
}
if (q <= start+leng || leng == std::string::npos) max = i;
if (min == std::string::npos || max == std::string::npos) return utf8("");
return str.substr(min,max);
}
//Modified code snippet from: http://stackoverflow.com/questions/6691555/converting-narrow-string-to-wide-string
std::wstring toWideString() {
if(wstr.size() == 0) {
wstr = std::wstring(size(), L' '); // Make room for characters
// Copy string to wstring.
std::copy(str.begin(), str.end(), wstr.begin());
}
return wstr;
}
};
*/
#endif /* Utf8_h */
|
74e2cbe20d8719d31450259037acda36fb059767 | 41472bbe0b29d9245fdb17eebee38824be627a5b | /src/physical_plan/separate.cpp | cf0e406f2df99c0da00b72025b6a899c7cdf27ec | [
"Apache-2.0"
] | permissive | baidu/BaikalDB | 0ff33c7c3792c733a4a4b1b58d3086e11fef8115 | e9e93899c4468044fdb63fa2b554948b24cb4541 | refs/heads/master | 2023-09-04T01:00:07.752637 | 2023-08-29T08:24:36 | 2023-08-29T08:24:36 | 143,436,277 | 1,193 | 189 | Apache-2.0 | 2023-09-14T04:08:51 | 2018-08-03T14:19:12 | C++ | UTF-8 | C++ | false | false | 48,920 | cpp | separate.cpp | // Copyright (c) 2018-present Baidu, Inc. 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 "separate.h"
#include "packet_node.h"
#include "limit_node.h"
#include "agg_node.h"
#include "scan_node.h"
#include "dual_scan_node.h"
#include "rocksdb_scan_node.h"
#include "join_node.h"
#include "sort_node.h"
#include "filter_node.h"
#include "full_export_node.h"
#include "insert_node.h"
#include "transaction_node.h"
#include "begin_manager_node.h"
#include "commit_manager_node.h"
#include "rollback_manager_node.h"
#include "insert_manager_node.h"
#include "update_manager_node.h"
#include "delete_manager_node.h"
#include "common_manager_node.h"
#include "select_manager_node.h"
#include "union_node.h"
#include "single_txn_manager_node.h"
#include "lock_primary_node.h"
#include "lock_secondary_node.h"
namespace baikaldb {
int Separate::analyze(QueryContext* ctx) {
if (ctx->is_explain && ctx->explain_type != SHOW_PLAN) {
return 0;
}
ExecNode* plan = ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
if (packet_node == nullptr) {
return -1;
}
if (packet_node->children_size() == 0 && !ctx->has_derived_table) {
return 0;
}
//DB_WARNING("need_seperate:%d", plan->need_seperate());
if (!plan->need_seperate() && !ctx->has_derived_table) {
return 0;
}
int ret = 0;
pb::OpType op_type = packet_node->op_type();
switch (op_type) {
case pb::OP_SELECT: {
ret = separate_select(ctx);
break;
}
case pb::OP_INSERT: {
ret = separate_insert(ctx);
break;
}
case pb::OP_UPDATE: {
ret = separate_update(ctx);
break;
}
case pb::OP_DELETE: {
ret = separate_delete(ctx);
break;
}
case pb::OP_TRUNCATE_TABLE: {
ret = separate_truncate(ctx);
break;
}
case pb::OP_KILL: {
ret = separate_kill(ctx);
break;
}
case pb::OP_BEGIN: {
ret = separate_begin(ctx);
break;
}
case pb::OP_COMMIT: {
ret = separate_commit(ctx);
break;
}
case pb::OP_ROLLBACK: {
ret = separate_rollback(ctx);
break;
}
case pb::OP_UNION: {
ret = separate_union(ctx);
break;
}
case pb::OP_LOAD: {
ret = separate_load(ctx);
break;
}
default: {
DB_FATAL("invalid op_type, op_type: %s", pb::OpType_Name(op_type).c_str());
return -1;
}
}
return ret;
}
int Separate::separate_union(QueryContext* ctx) {
ExecNode* plan = ctx->root;
UnionNode* union_node = static_cast<UnionNode*>(plan->get_node(pb::UNION_NODE));
for (size_t i = 0; i < ctx->sub_query_plans.size(); i++) {
auto select_ctx = ctx->sub_query_plans[i];
ExecNode* select_plan = select_ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(select_plan->get_node(pb::PACKET_NODE));
union_node->steal_projections(packet_node->mutable_projections());
union_node->add_child(packet_node->children(0));
packet_node->clear_children();
auto state = select_ctx->get_runtime_state();
if (state->init(select_ctx.get(), nullptr) < 0) {
DB_WARNING("init runtime_state failed");
return -1;
}
union_node->mutable_select_runtime_states()->emplace_back(state.get());
}
return 0;
}
int Separate::create_full_export_node(ExecNode* plan) {
_is_first_full_export = false;
std::vector<ExecNode*> scan_nodes;
plan->get_node(pb::SCAN_NODE, scan_nodes);
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
LimitNode* limit_node = static_cast<LimitNode*>(plan->get_node(pb::LIMIT_NODE));
std::unique_ptr<ExecNode> export_node(new (std::nothrow) FullExportNode);
if (export_node == nullptr) {
DB_WARNING("new export node fail");
return -1;
}
pb::PlanNode pb_fetch_node;
pb_fetch_node.set_node_type(pb::FULL_EXPORT_NODE);
pb_fetch_node.set_limit(-1);
export_node->init(pb_fetch_node);
std::map<int64_t, pb::RegionInfo> region_infos =
static_cast<RocksdbScanNode*>(scan_nodes[0])->region_infos();
export_node->set_region_infos(region_infos);
static_cast<RocksdbScanNode*>(scan_nodes[0])->set_related_manager_node(export_node.get());
if (limit_node != nullptr) {
export_node->add_child(limit_node->children(0));
limit_node->clear_children();
limit_node->add_child(export_node.release());
} else if (packet_node != nullptr) {
// 普通plan
export_node->add_child(packet_node->children(0));
packet_node->clear_children();
packet_node->add_child(export_node.release());
} else {
// apply plan
ExecNode* parent = plan->get_parent();
export_node->add_child(plan);
parent->replace_child(plan, export_node.release());
}
return 0;
}
int Separate::separate_select(QueryContext* ctx) {
ExecNode* plan = ctx->root;
std::vector<ExecNode*> join_nodes;
plan->get_node(pb::JOIN_NODE, join_nodes);
std::vector<ExecNode*> apply_nodes;
plan->get_node(pb::APPLY_NODE, apply_nodes);
if (join_nodes.size() == 0 && apply_nodes.size() == 0) {
return separate_simple_select(ctx, plan);
}
if (apply_nodes.size() > 0) {
int ret = separate_apply(ctx, apply_nodes);
if (ret < 0) {
return -1;
}
}
if (join_nodes.size() > 0) {
int ret = separate_join(ctx, join_nodes);
if (ret < 0) {
return -1;
}
}
return 0;
}
//普通的select请求,考虑agg_node, sort_node, limit_node下推问题
int Separate::separate_simple_select(QueryContext* ctx, ExecNode* plan) {
// join或者apply的情况下只有主表做full_export
if (ctx->is_full_export && _is_first_full_export) {
return create_full_export_node(plan);
}
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
LimitNode* limit_node = static_cast<LimitNode*>(plan->get_node(pb::LIMIT_NODE));
AggNode* agg_node = static_cast<AggNode*>(plan->get_node(pb::AGG_NODE));
SortNode* sort_node = static_cast<SortNode*>(plan->get_node(pb::SORT_NODE));
std::vector<ExecNode*> scan_nodes;
plan->get_node(pb::SCAN_NODE, scan_nodes);
SelectManagerNode* manager_node_inter = static_cast<SelectManagerNode*>(plan->get_node(pb::SELECT_MANAGER_NODE));
// 复用prepare的计划
if (manager_node_inter != nullptr) {
std::map<int64_t, pb::RegionInfo> region_infos =
static_cast<RocksdbScanNode*>(scan_nodes[0])->region_infos();
manager_node_inter->set_region_infos(region_infos);
return 0;
}
std::unique_ptr<SelectManagerNode> manager_node(create_select_manager_node());
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
if (scan_nodes.size() > 0) {
std::map<int64_t, pb::RegionInfo> region_infos =
static_cast<RocksdbScanNode*>(scan_nodes[0])->region_infos();
manager_node->set_region_infos(region_infos);
static_cast<RocksdbScanNode*>(scan_nodes[0])->set_related_manager_node(manager_node.get());
}
if (ctx->sub_query_plans.size() == 1) {
auto sub_query_ctx = ctx->sub_query_plans[0];
int ret = sub_query_ctx->get_runtime_state()->init(sub_query_ctx.get(), nullptr);
if (ret < 0) {
return -1;
}
manager_node->set_sub_query_runtime_state(sub_query_ctx->get_runtime_state().get());
auto iter = ctx->derived_table_ctx_mapping.begin();
int32_t tuple_id = iter->first;
manager_node->set_slot_column_mapping(ctx->slot_column_mapping[tuple_id]);
manager_node->set_derived_tuple_id(tuple_id);
ExecNode* sub_query_plan = sub_query_ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(sub_query_plan->get_node(pb::PACKET_NODE));
manager_node->steal_projections(packet_node->mutable_projections());
manager_node->set_sub_query_node(packet_node->children(0));
packet_node->clear_children();
FilterNode* filter_node = static_cast<FilterNode*>(plan->get_node(pb::WHERE_FILTER_NODE));
if (filter_node != nullptr) {
manager_node->add_child(filter_node->children(0));
filter_node->clear_children();
filter_node->add_child(manager_node.release());
return 0;
}
} else if (ctx->sub_query_plans.size() != 0) {
DB_WARNING("illegal plan, has multiple sub query ctx");
for (auto iter : ctx->sub_query_plans) {
DB_WARNING("sql:%s", iter->sql.c_str());
}
return -1;
}
if (agg_node != nullptr) {
ExecNode* parent = agg_node->get_parent();
pb::PlanNode pb_node;
agg_node->transfer_pb(0, &pb_node);
pb_node.set_node_type(pb::MERGE_AGG_NODE);
pb_node.set_limit(-1);
std::unique_ptr<AggNode> merge_agg_node(new (std::nothrow) AggNode);
merge_agg_node->init(pb_node);
if (ctx->sub_query_plans.size() > 0) {
parent->replace_child(agg_node, merge_agg_node.get());
merge_agg_node->add_child(agg_node);
merge_agg_node.release();
manager_node->add_child(agg_node->children(0));
agg_node->clear_children();
agg_node->add_child(manager_node.release());
return 0;
}
manager_node->add_child(agg_node);
merge_agg_node->add_child(manager_node.release());
parent->replace_child(agg_node, merge_agg_node.release());
return 0;
}
if (sort_node != nullptr) {
manager_node->init_sort_info(sort_node);
if (ctx->sub_query_plans.size() > 0) {
manager_node->add_child(sort_node->children(0));
sort_node->clear_children();
sort_node->add_child(manager_node.release());
return 0;
}
ExecNode* parent = sort_node->get_parent();
manager_node->add_child(sort_node);
parent->replace_child(sort_node, manager_node.release());
return 0;
}
if (limit_node != nullptr) {
manager_node->add_child(limit_node->children(0));
limit_node->clear_children();
limit_node->add_child(manager_node.release());
return 0;
}
if (packet_node != nullptr) {
// 普通plan
manager_node->add_child(packet_node->children(0));
packet_node->clear_children();
packet_node->add_child(manager_node.release());
} else {
// apply plan
ExecNode* parent = plan->get_parent();
manager_node->add_child(plan);
parent->replace_child(plan, manager_node.release());
}
return 0;
}
int Separate::separate_apply(QueryContext* ctx, const std::vector<ExecNode*>& apply_nodes) {
auto sperate_simple_plan = [this, ctx](ExecNode* plan) -> int {
std::vector<ExecNode*> join_nodes;
plan->get_node(pb::JOIN_NODE, join_nodes);
std::vector<ExecNode*> apply_nodes;
plan->get_node(pb::APPLY_NODE, apply_nodes);
if (join_nodes.size() == 0 && apply_nodes.size() == 0) {
int ret = separate_simple_select(ctx, plan);
if (ret < 0) {
return -1;
}
}
return 0;
};
for (auto& apply : apply_nodes) {
int ret = sperate_simple_plan(apply->children(0));
if (ret < 0) {
return -1;
}
ret = sperate_simple_plan(apply->children(1));
if (ret < 0) {
return -1;
}
}
return 0;
}
int Separate::separate_join(QueryContext* ctx, const std::vector<ExecNode*>& join_nodes) {
for (auto& join : join_nodes) {
std::vector<ExecNode*> scan_nodes;
join->join_get_scan_nodes(pb::SCAN_NODE, scan_nodes);
std::vector<ExecNode*> dual_scan_nodes;
join->join_get_scan_nodes(pb::DUAL_SCAN_NODE, dual_scan_nodes);
for (auto& scan_node_ptr : scan_nodes) {
ExecNode* manager_node_parent = scan_node_ptr->get_parent();
ExecNode* manager_node_child = scan_node_ptr;
if (manager_node_parent == nullptr) {
DB_WARNING("fether node children is null");
return -1;
}
while (manager_node_parent->node_type() == pb::TABLE_FILTER_NODE ||
manager_node_parent->node_type() == pb::WHERE_FILTER_NODE) {
manager_node_parent = manager_node_parent->get_parent();
manager_node_child = manager_node_child->get_parent();
if (manager_node_parent == nullptr) {
DB_WARNING("fether node children is null");
return -1;
}
}
// 复用prepare的计划
if (manager_node_parent->node_type() == pb::SELECT_MANAGER_NODE) {
std::map<int64_t, pb::RegionInfo> region_infos =
static_cast<RocksdbScanNode*>(scan_node_ptr)->region_infos();
manager_node_parent->set_region_infos(region_infos);
continue;
}
std::unique_ptr<ExecNode> manager_node;
// join或者apply的情况下只有主表做full_export
if (ctx->is_full_export && _is_first_full_export) {
_is_first_full_export = false;
manager_node.reset(new (std::nothrow) FullExportNode);
pb::PlanNode pb_fetch_node;
pb_fetch_node.set_node_type(pb::FULL_EXPORT_NODE);
pb_fetch_node.set_limit(-1);
manager_node->init(pb_fetch_node);
} else {
manager_node.reset(create_select_manager_node());
}
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
static_cast<RocksdbScanNode*>(scan_node_ptr)->set_related_manager_node(manager_node.get());
std::map<int64_t, pb::RegionInfo> region_infos =
static_cast<RocksdbScanNode*>(scan_node_ptr)->region_infos();
manager_node->set_region_infos(region_infos);
manager_node_parent->replace_child(manager_node_child, manager_node.get());
manager_node->add_child(manager_node_child);
manager_node.release();
}
for (auto& scan_node_ptr : dual_scan_nodes) {
DualScanNode* dual = static_cast<DualScanNode*>(scan_node_ptr);
auto iter = ctx->derived_table_ctx_mapping.find(dual->tuple_id());
if (iter == ctx->derived_table_ctx_mapping.end()) {
DB_WARNING("illegal plan table_id:%ld _tuple_id:%d", dual->table_id(), dual->tuple_id());
return -1;
}
int32_t tuple_id = iter->first;
auto sub_query_ctx = iter->second;
int ret = sub_query_ctx->get_runtime_state()->init(sub_query_ctx.get(), nullptr);
if (ret < 0) {
return -1;
}
ExecNode* manager_node_parent = scan_node_ptr->get_parent();
ExecNode* manager_node_child = scan_node_ptr;
if (manager_node_parent == nullptr) {
DB_WARNING("fether node children is null");
return -1;
}
std::unique_ptr<SelectManagerNode> manager_node(create_select_manager_node());
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
manager_node_parent->replace_child(manager_node_child, manager_node.get());
manager_node->add_child(manager_node_child);
manager_node->set_sub_query_runtime_state(sub_query_ctx->get_runtime_state().get());
manager_node->set_slot_column_mapping(ctx->slot_column_mapping[tuple_id]);
manager_node->set_derived_tuple_id(tuple_id);
ExecNode* sub_query_plan = sub_query_ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(sub_query_plan->get_node(pb::PACKET_NODE));
manager_node->steal_projections(packet_node->mutable_projections());
manager_node->set_sub_query_node(packet_node->children(0));
packet_node->clear_children();
manager_node.release();
}
// sort_node, limit_node pushdown,暂不考虑子查询
JoinNode* join_node = static_cast<JoinNode*>(join);
if ((join_node->join_type() != pb::LEFT_JOIN
&& join_node->join_type() != pb::RIGHT_JOIN)
|| ctx->sub_query_plans.size() > 0) {
continue;
}
LimitNode* limit_node = nullptr;
AggNode* agg_node = nullptr;
SortNode* sort_node = nullptr;
ExecNode* parent = join_node->get_parent();
while (parent->node_type() != pb::JOIN_NODE &&
parent != ctx->root) {
if (parent->node_type() == pb::LIMIT_NODE) {
limit_node = static_cast<LimitNode*>(parent);
}
if (parent->node_type() == pb::AGG_NODE) {
agg_node = static_cast<AggNode*>(parent);
}
if (parent->node_type() == pb::SORT_NODE) {
sort_node = static_cast<SortNode*>(parent);
}
parent = parent->get_parent();
}
if (agg_node != nullptr) {
continue;
} else if (limit_node != nullptr) {
parent = limit_node;
} else if (sort_node != nullptr) {
parent = sort_node->get_parent();
} else {
continue;
}
bool need_pushdown = true;
std::unordered_set<int32_t> *tuple_ids = nullptr;
ExecNode* node = nullptr;
if (join_node->join_type() == pb::LEFT_JOIN) {
tuple_ids = join_node->left_tuple_ids();
node = join_node->children(0);
} else if (join_node->join_type() == pb::RIGHT_JOIN) {
tuple_ids = join_node->right_tuple_ids();
node = join_node->children(1);
}
ExecNode* join_child = node;
while (node->children_size() > 0) {
if (node->node_type() == pb::JOIN_NODE) {
break;
}
if (node->node_type() == pb::SELECT_MANAGER_NODE) {
break;
}
node = node->children(0);
}
if (sort_node != nullptr) {
for (auto expr : sort_node->slot_order_exprs()) {
if(!join_node->expr_in_tuple_ids(*tuple_ids, expr)) {
need_pushdown = false;
break;
}
}
}
ExecNode* start = parent->children(0);
ExecNode* end = join->get_parent();
if (start == join) {
need_pushdown = false;
}
if (!need_pushdown) {
continue;
}
if (node->node_type() == pb::SELECT_MANAGER_NODE) {
// parent(limit)->sort->filter->join->manager->child =>
// parent(limit)->join->manager->sort->filter->child
SelectManagerNode* manager_node = static_cast<SelectManagerNode*>(node);
ExecNode* child = manager_node->children(0);
end->clear_children();
end->add_child(child);
manager_node->clear_children();
manager_node->add_child(start);
parent->replace_child(start, join);
if (sort_node != nullptr) {
manager_node->init_sort_info(sort_node);
}
} else if (node->node_type() == pb::JOIN_NODE) {
// parent(limit)->sort->filter->join->join_child->join2 =>
// parent(limit)->join->sort->filter->join_child->join2
ExecNode* child = join_child;
end->clear_children();
end->add_child(child);
join->replace_child(join_child, start);
parent->replace_child(start, join);
}
}
return 0;
}
bool Separate::need_separate_single_txn(QueryContext* ctx, const int64_t main_table_id) {
if (ctx->get_runtime_state()->single_sql_autocommit() &&
(ctx->enable_2pc
|| _factory->need_begin_txn(main_table_id)
|| ctx->open_binlog || ctx->execute_global_flow)) {
auto client = ctx->client_conn;
if (client != nullptr && client->txn_id == 0) {
client->on_begin();
}
return true;
}
return false;
}
bool Separate::need_separate_plan(QueryContext* ctx, const int64_t main_table_id) {
if (_factory->has_global_index(main_table_id) || ctx->execute_global_flow) {
return true;
}
return false;
}
int Separate::separate_load(QueryContext* ctx) {
ExecNode* plan = ctx->root;
InsertNode* insert_node = static_cast<InsertNode*>(plan->get_node(pb::INSERT_NODE));
ExecNode* parent = insert_node->get_parent();
pb::PlanNode pb_manager_node;
pb_manager_node.set_node_type(pb::INSERT_MANAGER_NODE);
pb_manager_node.set_limit(-1);
std::unique_ptr<InsertManagerNode> manager_node(new (std::nothrow) InsertManagerNode);
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
manager_node->init(pb_manager_node);
manager_node->set_records(ctx->insert_records);
int64_t main_table_id = insert_node->table_id();
if (ctx->row_ttl_duration > 0) {
manager_node->set_row_ttl_duration(ctx->row_ttl_duration);
_row_ttl_duration = ctx->row_ttl_duration;
}
if (!need_separate_plan(ctx, main_table_id)) {
manager_node->set_op_type(pb::OP_INSERT);
manager_node->set_region_infos(insert_node->region_infos());
manager_node->add_child(insert_node);
manager_node->set_table_id(main_table_id);
manager_node->set_selected_field_ids(insert_node->prepared_field_ids());
int ret = manager_node->init_insert_info(insert_node, true);
if (ret < 0) {
return -1;
}
} else {
int ret = separate_global_insert(manager_node.get(), insert_node);
if (ret < 0) {
DB_WARNING("separte global insert failed table_id:%ld", main_table_id);
return -1;
}
}
ctx->get_runtime_state()->set_single_txn_need_separate_execute(true);
parent->clear_children();
parent->add_child(manager_node.release());
if (need_separate_single_txn(ctx, main_table_id)) {
separate_single_txn(ctx, parent, pb::OP_INSERT);
}
return 0;
}
int Separate::separate_insert(QueryContext* ctx) {
ExecNode* plan = ctx->root;
InsertNode* insert_node = static_cast<InsertNode*>(plan->get_node(pb::INSERT_NODE));
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
// TODO:复用prepare的计划
pb::PlanNode pb_manager_node;
pb_manager_node.set_node_type(pb::INSERT_MANAGER_NODE);
pb_manager_node.set_limit(-1);
std::unique_ptr<InsertManagerNode> manager_node(new (std::nothrow) InsertManagerNode);
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
manager_node->init(pb_manager_node);
manager_node->set_records(ctx->insert_records);
if (ctx->row_ttl_duration > 0) {
manager_node->set_row_ttl_duration(ctx->row_ttl_duration);
_row_ttl_duration = ctx->row_ttl_duration;
}
int64_t main_table_id = insert_node->table_id();
if (!need_separate_plan(ctx, main_table_id)) {
manager_node->set_op_type(pb::OP_INSERT);
manager_node->set_region_infos(insert_node->region_infos());
manager_node->add_child(insert_node);
manager_node->set_table_id(main_table_id);
manager_node->set_selected_field_ids(insert_node->prepared_field_ids());
int ret = manager_node->init_insert_info(insert_node, true);
if (ret < 0) {
return -1;
}
} else {
int ret = separate_global_insert(manager_node.get(), insert_node);
if (ret < 0) {
DB_WARNING("separte global insert failed table_id:%ld", main_table_id);
return -1;
}
}
if (ctx->sub_query_plans.size() > 0) {
auto sub_query_ctx = ctx->sub_query_plans[0];
int ret = sub_query_ctx->get_runtime_state()->init(sub_query_ctx.get(), nullptr);
if (ret < 0) {
return -1;
}
manager_node->set_sub_query_runtime_state(sub_query_ctx->get_runtime_state().get());
ExecNode* sub_query_plan = sub_query_ctx->root;
// 单语句事务DML默认会和Prepare一起发送
ctx->get_runtime_state()->set_single_txn_need_separate_execute(true);
PacketNode* packet_node = static_cast<PacketNode*>(sub_query_plan->get_node(pb::PACKET_NODE));
manager_node->steal_projections(packet_node->mutable_projections());
manager_node->set_sub_query_node(packet_node->children(0));
packet_node->clear_children();
}
packet_node->clear_children();
packet_node->add_child(manager_node.release());
if (need_separate_single_txn(ctx, main_table_id)) {
separate_single_txn(ctx, packet_node, pb::OP_INSERT);
}
return 0;
}
// insert_node中的属性完全转义到manager_node中,析构insert_node
int Separate::separate_global_insert(InsertManagerNode* manager_node, InsertNode* insert_node) {
int64_t table_id = insert_node->table_id();
int ret = manager_node->init_insert_info(insert_node, false);
if (ret < 0) {
return -1;
}
// ignore
if (manager_node->need_ignore()) {
create_lock_node(table_id, pb::LOCK_GET, Separate::BOTH, manager_node);
create_lock_node(table_id, pb::LOCK_NO, Separate::BOTH, manager_node);
} else if (manager_node->is_replace()) {
create_lock_node(table_id, pb::LOCK_GET, Separate::BOTH, manager_node);
create_lock_node(table_id, pb::LOCK_GET_ONLY_PRIMARY, Separate::PRIMARY, manager_node);
create_lock_node(table_id, pb::LOCK_DML, Separate::BOTH, manager_node);
} else if (manager_node->on_dup_key_update()) {
create_lock_node(table_id, pb::LOCK_GET, Separate::BOTH, manager_node);
create_lock_node(table_id, pb::LOCK_GET_ONLY_PRIMARY, Separate::PRIMARY, manager_node);
create_lock_node(table_id, pb::LOCK_DML, Separate::BOTH, manager_node);
} else {
// basic insert
create_lock_node(table_id, pb::LOCK_DML, Separate::BOTH, manager_node);
}
// 复用
delete insert_node;
return 0;
}
int Separate::create_lock_node(
int64_t table_id,
pb::LockCmdType lock_type,
Separate::NodeMode mode,
ExecNode* manager_node) {
auto table_info = _factory->get_table_info_ptr(table_id);
if (table_info == nullptr) {
return -1;
}
std::vector<int64_t> global_affected_indexs;
std::vector<int64_t> global_unique_indexs;
std::vector<int64_t> global_non_unique_indexs;
std::vector<int64_t> local_affected_indexs;
for (auto index_id : table_info->indices) {
auto index_info = _factory->get_index_info_ptr(index_id);
if (index_info == nullptr) {
return -1;
}
if (index_info->index_hint_status == pb::IHS_VIRTUAL) {
DB_NOTICE("index info is virtual, skip.");
continue;
}
if (index_info->index_hint_status == pb::IHS_DISABLE
&& index_info->state == pb::IS_DELETE_LOCAL) {
continue;
}
if (index_info->is_global) {
if (index_info->state == pb::IS_NONE) {
DB_NOTICE("index info is NONE, skip.");
continue;
}
if (index_info->type == pb::I_UNIQ) {
global_unique_indexs.emplace_back(index_id);
} else if (lock_type != pb::LOCK_GET) {
//LOGK_GET只需要关注全局唯一索引
global_non_unique_indexs.emplace_back(index_id);
}
} else {
if (index_info->type == pb::I_UNIQ) {
local_affected_indexs.emplace_back(index_id);
} else if (lock_type != pb::LOCK_GET) {
//LOGK_GET只需要关注全局唯一索引
local_affected_indexs.emplace_back(index_id);
}
}
}
global_affected_indexs.insert(global_affected_indexs.end(), global_unique_indexs.begin(), global_unique_indexs.end());
global_affected_indexs.insert(global_affected_indexs.end(), global_non_unique_indexs.begin(), global_non_unique_indexs.end());
return create_lock_node(table_id, lock_type, mode, global_affected_indexs, local_affected_indexs, manager_node);
}
int Separate::create_lock_node(
int64_t table_id,
pb::LockCmdType lock_type,
Separate::NodeMode mode,
const std::vector<int64_t>& global_affected_indexs,
const std::vector<int64_t>& local_affected_indexs,
ExecNode* manager_node) {
//构造LockAndPutPrimaryNode
if (mode == Separate::BOTH || mode == Separate::PRIMARY) {
std::unique_ptr<LockPrimaryNode> primary_node(new (std::nothrow) LockPrimaryNode);
if (primary_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
pb::PlanNode plan_node;
plan_node.set_node_type(pb::LOCK_PRIMARY_NODE);
plan_node.set_limit(-1);
plan_node.set_num_children(0);
auto lock_primary_node = plan_node.mutable_derive_node()->mutable_lock_primary_node();
lock_primary_node->set_lock_type(lock_type);
lock_primary_node->set_table_id(table_id);
lock_primary_node->set_row_ttl_duration_s(_row_ttl_duration);
primary_node->init(plan_node);
primary_node->set_affected_index_ids(local_affected_indexs);
manager_node->add_child(primary_node.release());
}
//构造LockAndPutSecondaryNode
if (mode == Separate::BOTH || mode == Separate::GLOBAL) {
for (auto index_id : global_affected_indexs) {
std::unique_ptr<LockSecondaryNode> secondary_node(new (std::nothrow) LockSecondaryNode);
if (secondary_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
pb::PlanNode plan_node;
plan_node.set_node_type(pb::LOCK_SECONDARY_NODE);
plan_node.set_limit(-1);
plan_node.set_num_children(0);
auto lock_secondary_node = plan_node.mutable_derive_node()->mutable_lock_secondary_node();
lock_secondary_node->set_lock_type(lock_type);
lock_secondary_node->set_global_index_id(index_id);
lock_secondary_node->set_table_id(table_id);
lock_secondary_node->set_row_ttl_duration_s(_row_ttl_duration);
secondary_node->init(plan_node);
manager_node->add_child(secondary_node.release());
}
}
return 0;
}
int Separate::separate_update(QueryContext* ctx) {
int ret = 0;
ExecNode* plan = ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
UpdateNode* update_node = static_cast<UpdateNode*>(plan->get_node(pb::UPDATE_NODE));
std::vector<ExecNode*> scan_nodes;
plan->get_node(pb::SCAN_NODE, scan_nodes);
pb::PlanNode pb_manager_node;
pb_manager_node.set_node_type(pb::UPDATE_MANAGER_NODE);
pb_manager_node.set_limit(-1);
std::unique_ptr<UpdateManagerNode> manager_node(new (std::nothrow) UpdateManagerNode);
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
manager_node->init(pb_manager_node);
ret = manager_node->init_update_info(update_node);
if (ret < 0) {
return -1;
}
int64_t main_table_id = update_node->table_id();
if (!need_separate_plan(ctx, main_table_id)) {
auto region_infos = static_cast<RocksdbScanNode*>(scan_nodes[0])->region_infos();
manager_node->set_op_type(pb::OP_UPDATE);
manager_node->set_region_infos(region_infos);
manager_node->add_child(packet_node->children(0));
} else {
ret = separate_global_update(manager_node.get(), update_node, scan_nodes[0]);
if (ret < 0) {
DB_WARNING("separte global update failed table_id:%ld", main_table_id);
return -1;
}
}
packet_node->clear_children();
packet_node->add_child(manager_node.release());
if (need_separate_single_txn(ctx, main_table_id)) {
separate_single_txn(ctx, packet_node, pb::OP_UPDATE);
}
return 0;
}
int Separate::separate_delete(QueryContext* ctx) {
ExecNode* plan = ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
DeleteNode* delete_node = static_cast<DeleteNode*>(plan->get_node(pb::DELETE_NODE));
std::vector<ExecNode*> scan_nodes;
plan->get_node(pb::SCAN_NODE, scan_nodes);
int64_t main_table_id = delete_node->table_id();
pb::PlanNode pb_manager_node;
pb_manager_node.set_node_type(pb::DELETE_MANAGER_NODE);
pb_manager_node.set_limit(-1);
std::unique_ptr<DeleteManagerNode> manager_node(new (std::nothrow) DeleteManagerNode);
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
manager_node->init(pb_manager_node);
int ret = manager_node->init_delete_info(delete_node->pb_node().derive_node().delete_node());
if (ret < 0) {
return -1;
}
if (!need_separate_plan(ctx, main_table_id)) {
auto region_infos = static_cast<RocksdbScanNode*>(scan_nodes[0])->region_infos();
manager_node->set_op_type(pb::OP_DELETE);
manager_node->set_region_infos(region_infos);
manager_node->add_child(packet_node->children(0));
} else {
int ret = separate_global_delete(manager_node.get(), delete_node, scan_nodes[0]);
if (ret < 0) {
DB_WARNING("separte global delete failed table_id:%ld", main_table_id);
return -1;
}
}
packet_node->clear_children();
packet_node->add_child(manager_node.release());
if (need_separate_single_txn(ctx, main_table_id)) {
separate_single_txn(ctx, packet_node, pb::OP_DELETE);
}
return 0;
}
int Separate::separate_global_update(
UpdateManagerNode* manager_node,
UpdateNode* update_node,
ExecNode* scan_node) {
int ret = 0;
int64_t main_table_id = update_node->table_id();
//生成delete_node_manager结点
pb::PlanNode pb_delete_manager_node;
pb_delete_manager_node.set_node_type(pb::DELETE_MANAGER_NODE);
pb_delete_manager_node.set_limit(-1);
std::unique_ptr<DeleteManagerNode> delete_manager_node(new (std::nothrow) DeleteManagerNode);
if (delete_manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
delete_manager_node->init(pb_delete_manager_node);
ret = delete_manager_node->init_delete_info(update_node->pb_node().derive_node().update_node());
if (ret < 0) {
return -1;
}
std::unique_ptr<SelectManagerNode> select_manager_node(create_select_manager_node());
if (select_manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
select_manager_node->set_region_infos(scan_node->region_infos());
select_manager_node->add_child(update_node->children(0));
delete_manager_node->add_child(select_manager_node.release());
manager_node->set_update_exprs(update_node->update_exprs());
update_node->clear_children();
update_node->clear_update_exprs();
delete update_node;
create_lock_node(
main_table_id,
pb::LOCK_GET_DML,
Separate::PRIMARY,
manager_node->global_affected_index_ids(),
manager_node->local_affected_index_ids(),
delete_manager_node.get());
create_lock_node(
main_table_id,
pb::LOCK_DML,
Separate::GLOBAL,
manager_node->global_affected_index_ids(),
manager_node->local_affected_index_ids(),
delete_manager_node.get());
LockPrimaryNode* pri_node = static_cast<LockPrimaryNode*>(delete_manager_node->children(1));
pri_node->set_affect_primary(manager_node->affect_primary());
FilterNode* where_filter_node = static_cast<FilterNode*>(delete_manager_node->get_node(pb::WHERE_FILTER_NODE));
if (where_filter_node != nullptr) {
for (auto conjunct : *(where_filter_node->mutable_conjuncts())) {
pri_node->add_conjunct(conjunct);
}
}
FilterNode* table_filter_node = static_cast<FilterNode*>(delete_manager_node->get_node(pb::TABLE_FILTER_NODE));
if (table_filter_node != nullptr) {
for (auto conjunct : *(table_filter_node->mutable_conjuncts())) {
pri_node->add_conjunct(conjunct);
}
}
manager_node->add_child(delete_manager_node.release());
//生成basic_insert
pb::PlanNode pb_insert_manager_node;
pb_insert_manager_node.set_node_type(pb::INSERT_MANAGER_NODE);
pb_insert_manager_node.set_limit(-1);
std::unique_ptr<InsertManagerNode> insert_manager_node(new (std::nothrow) InsertManagerNode);
if (insert_manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
insert_manager_node->init(pb_insert_manager_node);
create_lock_node(main_table_id, pb::LOCK_DML, Separate::BOTH,
manager_node->global_affected_index_ids(),
manager_node->local_affected_index_ids(),
insert_manager_node.get());
pri_node = static_cast<LockPrimaryNode*>(insert_manager_node->children(0));
pri_node->set_affect_primary(manager_node->affect_primary());
manager_node->add_child(insert_manager_node.release());
return 0;
}
/*
* packetNode
* |
* DeleteMangerNode
* |
* SelectManagerNode LockPrimaryNode LockSecondaryNode
* |
* FilterNode
* |
* ScanNode
*
*/
int Separate::separate_global_delete(
DeleteManagerNode* manager_node,
DeleteNode* delete_node,
ExecNode* scan_node) {
int64_t main_table_id = delete_node->table_id();
std::unique_ptr<SelectManagerNode> select_manager_node(create_select_manager_node());
if (select_manager_node.get() == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
std::map<int64_t, pb::RegionInfo> region_infos =
static_cast<RocksdbScanNode*>(scan_node)->region_infos();
select_manager_node->set_region_infos(region_infos);
select_manager_node->add_child(delete_node->children(0));
manager_node->add_child(select_manager_node.release());
delete_node->clear_children();
create_lock_node(main_table_id, pb::LOCK_GET_DML, Separate::PRIMARY, manager_node);
create_lock_node(main_table_id, pb::LOCK_DML, Separate::GLOBAL, manager_node);
// manager_node->children(0)->add_child(delete_node->children(0));
LockPrimaryNode* pri_node = static_cast<LockPrimaryNode*>(manager_node->children(1));
FilterNode* where_filter_node = static_cast<FilterNode*>(manager_node->get_node(pb::WHERE_FILTER_NODE));
if (where_filter_node != nullptr) {
for (auto conjunct : *(where_filter_node->mutable_conjuncts())) {
pri_node->add_conjunct(conjunct);
}
}
FilterNode* table_filter_node = static_cast<FilterNode*>(manager_node->get_node(pb::TABLE_FILTER_NODE));
if (table_filter_node != nullptr) {
for (auto conjunct : *(table_filter_node->mutable_conjuncts())) {
pri_node->add_conjunct(conjunct);
}
}
delete delete_node;
return 0;
}
template<typename T>
int Separate::separate_single_txn(QueryContext* ctx, T* node, pb::OpType op_type) {
// create baikaldb commit node
pb::PlanNode pb_plan_node;
pb_plan_node.set_node_type(pb::SIGNEL_TXN_MANAGER_NODE);
pb_plan_node.set_limit(-1);
pb_plan_node.set_num_children(5);
SingleTxnManagerNode* txn_manager_node = new (std::nothrow) SingleTxnManagerNode;
if (txn_manager_node == nullptr) {
DB_WARNING("create store_txn_node failed");
return -1;
}
txn_manager_node->init(pb_plan_node);
txn_manager_node->set_op_type(op_type);
ExecNode* dml_root = node->children(0);
node->clear_children();
node->add_child(txn_manager_node);
// create store begin node
std::unique_ptr<TransactionNode> store_begin_node(create_txn_node(pb::TXN_BEGIN_STORE, ctx->user_info->txn_lock_timeout));
if (store_begin_node.get() == nullptr) {
DB_WARNING("create store_begin_node failed");
return -1;
}
// create store prepare node
std::unique_ptr<TransactionNode> store_prepare_node(create_txn_node(pb::TXN_PREPARE));
if (store_prepare_node.get() == nullptr) {
DB_WARNING("create store_prepare_node failed");
return -1;
}
// create store commit node
std::unique_ptr<TransactionNode> store_commit_node(create_txn_node(pb::TXN_COMMIT_STORE));
if (store_commit_node.get() == nullptr) {
DB_WARNING("create store_commit_node failed");
return -1;
}
// create store rollback node
std::unique_ptr<TransactionNode> store_rollback_node(create_txn_node(pb::TXN_ROLLBACK_STORE));
if (store_rollback_node.get() == nullptr) {
DB_WARNING("create store_rollback_node failed");
return -1;
}
txn_manager_node->add_child(store_begin_node.release());
txn_manager_node->add_child(dml_root);
txn_manager_node->add_child(store_prepare_node.release());
txn_manager_node->add_child(store_commit_node.release());
txn_manager_node->add_child(store_rollback_node.release());
return 0;
}
int Separate::separate_truncate(QueryContext* ctx) {
ExecNode* plan = ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
pb::PlanNode pb_manager_node;
pb_manager_node.set_node_type(pb::TRUNCATE_MANAGER_NODE);
pb_manager_node.set_limit(-1);
std::unique_ptr<CommonManagerNode> manager_node(new (std::nothrow) CommonManagerNode);
if (manager_node.get() == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
manager_node->init(pb_manager_node);
manager_node->set_op_type(pb::OP_TRUNCATE_TABLE);
manager_node->set_region_infos(packet_node->children(0)->region_infos());
manager_node->add_child(packet_node->children(0));
packet_node->clear_children();
packet_node->add_child(manager_node.release());
return 0;
}
int Separate::separate_kill(QueryContext* ctx) {
ExecNode* plan = ctx->root;
PacketNode* packet_node = static_cast<PacketNode*>(plan->get_node(pb::PACKET_NODE));
pb::PlanNode pb_manager_node;
pb_manager_node.set_node_type(pb::KILL_MANAGER_NODE);
pb_manager_node.set_limit(-1);
std::unique_ptr<CommonManagerNode> manager_node(new (std::nothrow) CommonManagerNode);
if (manager_node.get() == nullptr) {
DB_WARNING("create manager_node failed");
return -1;
}
manager_node->init(pb_manager_node);
manager_node->set_op_type(pb::OP_KILL);
manager_node->set_region_infos(packet_node->children(0)->region_infos());
manager_node->add_child(packet_node->children(0));
packet_node->clear_children();
packet_node->add_child(manager_node.release());
return 0;
}
int Separate::separate_commit(QueryContext* ctx) {
ExecNode* plan = ctx->root;
CommitManagerNode* commit_node =
static_cast<CommitManagerNode*>(plan->get_node(pb::COMMIT_MANAGER_NODE));
std::unique_ptr<TransactionNode> store_prepare_node(create_txn_node(pb::TXN_PREPARE));
if (store_prepare_node.get() == nullptr) {
DB_WARNING("create store_prepare_node failed");
return -1;
}
commit_node->add_child(store_prepare_node.release());
// create store commit node
std::unique_ptr<TransactionNode> store_commit_node(create_txn_node(pb::TXN_COMMIT_STORE));
if (store_commit_node.get() == nullptr) {
DB_WARNING("create store_commit_node failed");
return -1;
}
// create store rollback node
std::unique_ptr<TransactionNode> store_rollback_node(create_txn_node(pb::TXN_ROLLBACK_STORE));
if (store_rollback_node.get() == nullptr) {
DB_WARNING("create store_rollback_node failed");
return -1;
}
commit_node->add_child(store_commit_node.release());
commit_node->add_child(store_rollback_node.release());
if (commit_node->txn_cmd() == pb::TXN_COMMIT_BEGIN) {
// create store begin node
std::unique_ptr<TransactionNode> store_begin_node(create_txn_node(pb::TXN_BEGIN_STORE, ctx->user_info->txn_lock_timeout));
if (store_begin_node.get() == nullptr) {
DB_WARNING("create store_begin_node failed");
return -1;
}
commit_node->add_child(store_begin_node.release());
}
return 0;
}
int Separate::separate_rollback(QueryContext* ctx) {
ExecNode* plan = ctx->root;
RollbackManagerNode* rollback_node =
static_cast<RollbackManagerNode*>(plan->get_node(pb::ROLLBACK_MANAGER_NODE));
// create store rollback node
std::unique_ptr<TransactionNode> store_rollback_node(create_txn_node(pb::TXN_ROLLBACK_STORE));
if (store_rollback_node.get() == nullptr) {
DB_WARNING("create store_rollback_node failed");
return -1;
}
rollback_node->add_child(store_rollback_node.release());
if (rollback_node->txn_cmd() == pb::TXN_ROLLBACK_BEGIN) {
// create store begin node
std::unique_ptr<TransactionNode> store_begin_node(create_txn_node(pb::TXN_BEGIN_STORE, ctx->user_info->txn_lock_timeout));
if (store_begin_node.get() == nullptr) {
DB_WARNING("create store_begin_node failed");
return -1;
}
rollback_node->add_child(store_begin_node.release());
}
return 0;
}
int Separate::separate_begin(QueryContext* ctx) {
ExecNode* plan = ctx->root;
BeginManagerNode* begin_node =
static_cast<BeginManagerNode*>(plan->get_node(pb::BEGIN_MANAGER_NODE));
// create store begin node
std::unique_ptr<TransactionNode> store_begin_node(create_txn_node(pb::TXN_BEGIN_STORE, ctx->user_info->txn_lock_timeout));
if (store_begin_node.get() == nullptr) {
DB_WARNING("create store_begin_node failed");
return -1;
}
begin_node->add_child(store_begin_node.release());
return 0;
}
TransactionNode* Separate::create_txn_node(pb::TxnCmdType cmd_type, int64_t txn_lock_timeout) {
// create fetcher node
pb::PlanNode pb_plan_node;
// pb_plan_node.set_txn_id(txn_id);
pb_plan_node.set_node_type(pb::TRANSACTION_NODE);
pb_plan_node.set_limit(-1);
pb_plan_node.set_num_children(0);
auto txn_node = pb_plan_node.mutable_derive_node()->mutable_transaction_node();
txn_node->set_txn_cmd(cmd_type);
// create store txn node
TransactionNode* store_txn_node = new (std::nothrow) TransactionNode;
if (store_txn_node == nullptr) {
DB_WARNING("create store_txn_node failed");
return nullptr;
}
if (txn_lock_timeout > 0) {
store_txn_node->set_txn_lock_timeout(txn_lock_timeout);
}
store_txn_node->init(pb_plan_node);
return store_txn_node;
}
SelectManagerNode* Separate::create_select_manager_node() {
pb::PlanNode pb_manager_node;
pb_manager_node.set_node_type(pb::SELECT_MANAGER_NODE);
pb_manager_node.set_limit(-1);
SelectManagerNode* manager_node = new (std::nothrow) SelectManagerNode;
if (manager_node == nullptr) {
DB_WARNING("create manager_node failed");
return nullptr;
}
manager_node->init(pb_manager_node);
return manager_node;
}
} // namespace baikaldb
/* vim: set ts=4 sw=4 sts=4 tw=100 */
|
4ded1b62fe34a79b67b8e3bd8c30f9a4c896dcb7 | 1e8811d2758e199f696ef04b4ed34dc510ec1e03 | /Substraction.cpp | 020376d4606bb93f615363748b545a6d8784cc86 | [] | no_license | peipei0w0/Arithmetic | d92b96a9ea42e02c0a835eb5873e0b7838c334d0 | faf2d5b4755995d54422dbe94bc49793b062d488 | refs/heads/master | 2020-12-04T09:30:27.378159 | 2020-05-13T06:37:59 | 2020-05-13T06:37:59 | 231,012,093 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 190 | cpp | Substraction.cpp | #include<iostream>
using namespace std;
int main(){
int num1,num2;
cout<<"請輸入要相減的2個數字"<<endl;
cin>>num1>>num2;
cout<<"兩數之差為:"<<num1-num2<<endl;
}
|
421ff5ae41d3043ac52d24ab5f12ce080cacb69d | 19fe3e019ff4cb4e1476799d681a876928431174 | /src/scene/tools/vcAddBoxFilter.cpp | 5b90025c7e55f6661f89a5a2bcd9fc9f225551a5 | [
"MIT"
] | permissive | etsangsplk/vaultclient | e113f70734ea5bdc15581715bd94fb492d1a94d4 | d09eb3891109c2ff8ee31bcee152be95dfe78b2e | refs/heads/master | 2022-12-12T12:28:26.774190 | 2020-08-27T04:39:52 | 2020-08-27T04:39:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | cpp | vcAddBoxFilter.cpp | #include "vcAddBoxFilter.h"
#include "vcState.h"
#include "vcStrings.h"
#include "udStringUtil.h"
#include "imgui.h"
vcAddBoxFilter vcAddBoxFilter::m_instance;
void vcAddBoxFilter::SceneUI(vcState *pProgramState)
{
if ((pProgramState->sceneExplorer.selectedItems.size() == 1) && (pProgramState->sceneExplorer.selectedItems[0].pItem->pUserData != nullptr))
{
vcSceneItem *pSceneItem = (vcSceneItem *)pProgramState->sceneExplorer.selectedItems[0].pItem->pUserData;
pSceneItem->HandleSceneEmbeddedUI(pProgramState);
}
}
|
157fdd435898b0658faa74a74394dbdf22474ab1 | 7c3a04360b385f7baf694d2778bd009fd3370ff5 | /kata/c++/data structures/stack/Combination.hpp | e094b72d3e88770aa1ae75ed4e5c64d52ed961d4 | [] | no_license | birneysky/Playgrounds | 43e23fa9f951ce13cd97b95c6598326981395fb2 | 0b850928cfb22e6264cf3a709ce534f37ea67dec | refs/heads/master | 2023-01-07T21:41:59.708555 | 2022-12-20T04:00:10 | 2022-12-20T04:00:10 | 181,522,354 | 4 | 1 | null | 2022-09-14T12:22:44 | 2019-04-15T16:08:22 | Jupyter Notebook | UTF-8 | C++ | false | false | 1,129 | hpp | Combination.hpp | //
// Combination.hpp
// KataTest
//
// Created by birney on 2020/9/8.
//
#ifndef Combination_hpp
#define Combination_hpp
#include <vector>
/* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
**/
class Combination {
private:
std::vector<std::vector<int>> result;
/// 求解 C(n,k), 当前已经找到的组合存储在 c 中, 需要从 star t开始搜索新的元素
void _combine(int start, int n, int k, std::vector<int>& c) {
if (c.size() == k) {
result.push_back(c);
return;
}
for (int i = start; i <= n; i++) {
c.push_back(i);
_combine(i + 1, n, k, c);
c.pop_back();
}
}
public:
std::vector<std::vector<int>> combine(int n, int k) {
result.clear();
std::vector<int> c;
_combine(1, n, k, c);
return result;
}
};
#endif /* Combination_hpp */
|
6593c1b0021e47bb759c8afa69b5a5dc708c9746 | a5b79c90312d63f50d4f359bf4d564b3e6a548ec | /kmc_rate.h | 3b5699e56167d6f54b903de92176f368fcddc04f | [] | no_license | JasonGyy/kmc-solute-diffusion-fcc | d75c10b1b2e056a71ce0d7f1a48ca5eb9a84e748 | 254e6b021acb243602ee70f7f6842169478a7851 | refs/heads/master | 2021-06-15T23:00:30.406163 | 2017-05-04T17:08:06 | 2017-05-04T17:08:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | h | kmc_rate.h | /* KMC Simulation for FCC lattice with diffusion
by species swap and/or vacancy exchange
Author: Tegar Wicaksono (tegar@alumni.ubc.ca)
Written: March 2017
Check repository below for the most updated version:
https://github.com/tegarwicaksono/kmc-solute-diffusion-fcc
*/
#ifndef KMC_RATE_H_INCLUDED
#define KMC_RATE_H_INCLUDED
#include "kmc_movingspecies.h"
#include <utility>
class Rate {
public:
MovingSpecies* species;
int direction;
double cumulative;
Rate();
Rate(MovingSpecies* const &species, const int &direction);
Rate(const Rate& other);
Rate(Rate&& other);
Rate& operator= (Rate other);
virtual ~Rate() = default;
friend void swap(Rate &a, Rate &b);
void print();
};
#endif // KMC_RATE_H_INCLUDED
|
6afb88c5aa3f7d10d57e303e0f01930624f7f001 | ea3d550a36ef78610449a34f4aa3fa5308c7125d | /HookDll/Shared/FileUtils.h | c18e7a1cf6644bec89a1fe95cc75049108300b59 | [
"MIT"
] | permissive | marius00/iagd | 8bd972be95bc5ea2529b3e03cf29f1a59e96a6ab | 67340078e7bbcf2b5bdce1ec23d50703a87e8745 | refs/heads/master | 2023-04-28T03:05:41.253835 | 2022-12-24T19:46:22 | 2022-12-24T19:46:22 | 114,466,693 | 100 | 34 | MIT | 2023-04-19T18:13:30 | 2017-12-16T14:27:51 | C# | UTF-8 | C++ | false | false | 253 | h | FileUtils.h | #pragma once
#include <shared/UnicodeSupport.h>
std::tstring BrowseForFolder(HWND hWndOwner, std::tstring const& title);
std::tstring BrowseForOutputFile(HWND hWndOwner, std::tstring const& title, TCHAR* filter, std::tstring const& defaultExtension);
|
33f2c7a0cd100e9506f949a40a8520274d94889d | 030822e702e990a9ed4f3ee45028bbb8f939e7bd | /CG/OpenGL2/COP/Chirag/SubdivideComplete.h | 6b1a126c3078b9ae3e72f488562da1b37a70e1a7 | [] | no_license | tanmaybinaykiya/codebin | 962a9efc51e11d0991e67e8f49e2a8560de70020 | 9ffeea83dc9a54cdabe0941d5669f0f50ded2cff | refs/heads/master | 2021-01-17T08:52:51.043517 | 2016-04-10T19:21:36 | 2016-04-10T19:21:46 | 6,626,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,988 | h | SubdivideComplete.h | #include <GL/glut.h>
#include <stdio.h>
#include <memory.h>
#pragma warning (disable:4018)
#pragma warning (disable:4101)
#ifndef M_PI
#define M_PI 3.14159265f
#endif
class Triangle {
public :
Triangle(){memset(this,0,sizeof(Triangle));}
GLuint verts[3];
} ;
class Vertex {
public :
Vertex(){memset(this,0,sizeof(Vertex)) ;}
GLfloat x, y, z;
GLboolean newpoint;
class Vertex* averaged; /* used for subdivision */
class Vertex* next; /* no geometric meaning - just a list */
} ;
class Edge {
public :
Edge(){memset(this,0,sizeof(Edge)) ;}
class Vertex* head;
class Vertex* tail;
class Edge* next;
class Edge* prev;
class Edge* twin;
class Face* left;
class Face* right;
} ;
class Face {
public :
Face(){ memset(this,0,sizeof(Face)) ;}
class Edge* edge;
class Vertex* normal;
class Face* next; /* no geometric meaning - just a list */
} ;
class WingedEdge {
public :
WingedEdge(){memset(this,0,sizeof(WingedEdge)) ;}
class Face* faces;
class Vertex* vertices;
/* edges are already uniquely ordered by the faces */
} ;
class Model {
public :
Model(){memset(this,0,sizeof(Model)) ;}
GLuint numVertices;
GLuint numFaces;
Vertex* position;
} ;
WingedEdge* readOBJ(char* filename);
GLvoid firstPass(Model* model, FILE* file);
WingedEdge* secondPass(Model* model, FILE* file);
GLfloat unitize(WingedEdge* we);
GLvoid facetNormals(WingedEdge* we);
GLvoid vertexNormals(WingedEdge* we);
GLfloat sabs(GLfloat f);
GLfloat smax(GLfloat a, GLfloat b);
GLfloat sdot(Vertex* u, Vertex* v);
Vertex* scross(Vertex* u, Vertex* v);
GLvoid snormalize(Vertex* v);
GLvoid subdivide(WingedEdge* we);
GLvoid firstDivision(Face* face);
GLvoid secondDivision(Face* face);
GLvoid refine(WingedEdge* we);
Vertex* midpoint(Vertex* v1, Vertex* v2);
long faceCount(WingedEdge* we);
long vertexCount(WingedEdge* we);
void wireObject(WingedEdge* we) ;
void flatObject(WingedEdge* we) ;
|
622a389a257aaa3572bbc4bd5203b3c863ef3875 | d4d356ae6a7391b95f820108e4d3b0fef05506d2 | /test/exchange.cpp | 5f80bbf691d127c4a46f45215df7ca3a892e06c3 | [
"MIT"
] | permissive | TyRoXx/silicium | 27729b01e76a8947d68b569841bf8f1923a21793 | 3a19b81f05ff487df4f314f204f1d10e4d272fee | refs/heads/master | 2021-01-23T08:39:44.336205 | 2017-03-03T23:54:33 | 2017-03-03T23:54:33 | 20,037,983 | 4 | 1 | MIT | 2018-11-26T09:17:34 | 2014-05-21T21:26:14 | C++ | UTF-8 | C++ | false | false | 1,402 | cpp | exchange.cpp | #include <silicium/exchange.hpp>
#include <silicium/make_unique.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(exchange_noexcept_true)
{
auto p = Si::make_unique<int>(123);
auto r = Si::make_unique<int>(456);
auto q = Si::exchange(p, std::move(r));
BOOST_CHECK(!r);
BOOST_REQUIRE(p);
BOOST_REQUIRE(q);
BOOST_CHECK_EQUAL(456, *p);
BOOST_CHECK_EQUAL(123, *q);
}
struct non_noexcept_movable
{
int state;
non_noexcept_movable()
: state(0)
{
}
non_noexcept_movable(non_noexcept_movable const &other)
: state(other.state)
{
}
non_noexcept_movable(non_noexcept_movable &&other) BOOST_NOEXCEPT_IF(false)
: state(other.state)
{
other.state = 0;
}
non_noexcept_movable &operator=(non_noexcept_movable const &other)
{
state = other.state;
return *this;
}
non_noexcept_movable &operator=(non_noexcept_movable &&other)
BOOST_NOEXCEPT_IF(false)
{
state = other.state;
other.state = 0;
return *this;
}
};
BOOST_AUTO_TEST_CASE(exchange_noexcept_false)
{
non_noexcept_movable a;
a.state = 123;
non_noexcept_movable b;
b.state = 456;
non_noexcept_movable c = Si::exchange(a, std::move(b));
BOOST_CHECK_EQUAL(456, a.state);
BOOST_CHECK_EQUAL(123, c.state);
BOOST_CHECK_EQUAL(0, b.state);
}
|
3e18f670f41785d6ae3b2524edd60feb7752c2a2 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /Trigger/TrigSteer/DecisionHandling/DecisionHandling/ComboHypo.h | ef7151cc847694c70ebffcfd65392689ca82b7c5 | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,038 | h | ComboHypo.h | /*
Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
*/
#ifndef DECISIONHANDLING_COMBOHYPO_H
#define DECISIONHANDLING_COMBOHYPO_H
// Framework includes
#include "AthenaBaseComps/AthReentrantAlgorithm.h"
#include "TrigCompositeUtils/TrigCompositeUtils.h"
// STL includes
#include <string>
#include <utility>
#include "DecisionHandling/ComboHypoToolBase.h"
/**
* @class ComboHypo for combined hypotheses required only counting (multiplicity requirements)
* @warning while configuring it the order of specified multiplicities has to match order of input decision containers
* i.e. if feed with:
* electronDecisions
* muonDecisions
* jetDecisions
* the multiplicity specification like this:
* "HLT_4e10_2mu7_j100" : [ 4, 2, 1 ] will apply respectively requirement of 4, 2, 1 positive decisions in electron, muon and jet inputs
**/
class ComboHypo : public ::AthReentrantAlgorithm {
public:
ComboHypo(const std::string& name, ISvcLocator* pSvcLocator);
virtual ~ComboHypo() override;
virtual StatusCode initialize() override;
virtual StatusCode execute(const EventContext& context) const override;
virtual StatusCode finalize() override;
protected:
const SG::ReadHandleKeyArray<TrigCompositeUtils::DecisionContainer>& decisionsInput() const { return m_inputs; }
const SG::WriteHandleKeyArray<TrigCompositeUtils::DecisionContainer>& decisionsOutput() const { return m_outputs; }
typedef std::map<std::string, std::vector<int>> MultiplicityReqMap;
const MultiplicityReqMap& triggerMultiplicityMap() const { return m_multiplicitiesReqMap.value(); }
ToolHandleArray<ComboHypoToolBase>& hypoTools() { return m_hypoTools; }
const ToolHandleArray<ComboHypoToolBase>& hypoTools() const { return m_hypoTools; }
private:
SG::ReadHandleKeyArray<TrigCompositeUtils::DecisionContainer> m_inputs { this, "HypoInputDecisions", {}, "Input Decisions" };
SG::WriteHandleKeyArray<TrigCompositeUtils::DecisionContainer> m_outputs { this, "HypoOutputDecisions", {}, "Ouput Decisions" };
Gaudi::Property<bool> m_requireUniqueROI {this, "RequireUniqueROI", false,
"Require each Feature in each leg of the combination to come from a unique L1 seeding ROI."};
Gaudi::Property< MultiplicityReqMap > m_multiplicitiesReqMap{this, "MultiplicitiesMap", {},
"Map from the chain name to multiplicities required at each input"};
Gaudi::Property<bool> m_checkMultiplicityMap { this, "CheckMultiplicityMap", true,
"Perform a consistency check of the MultiplicitiesMap"};
/**
* @brief iterates over the inputs and for every object (no filtering) crates output object linked to input moving
* the decisions that are mentioned in the passing set
**/
StatusCode copyDecisions( const LegDecisionsMap & passingLegs, const EventContext& context ) const;
/**
* @brief For a given Decision node from a HypoAlg, extracts type-less identification data on the node's Feature and seeding ROI.
* @param[in] d The Decision node from the HypoAlg, expected to have a "feature" link attached to it.
* Expected to be able to locate a "initialRoI" in its history if RequireUniqueROI=True.
* @param[out] featureKey Type-less SG Key hash of the collection hosting the Decision node's feature .
* @param[out] featureIndex Index inside the featureKey collection.
* @param[out] roiKey Type-less SG Key hash of the collection hosting the Decision node's initial ROI collection.
* @param[out] roiIndex Index inside the roiKey collection.
**/
StatusCode extractFeatureAndRoI(const ElementLink<TrigCompositeUtils::DecisionContainer>& EL,
uint32_t& featureKey, uint16_t& featureIndex, uint32_t& roiKey, uint16_t& roiIndex) const;
/**
* @brief iterates over all inputs, associating inputs to legs
**/
StatusCode fillDecisionsMap( LegDecisionsMap& dmap, const EventContext& context) const;
ToolHandleArray< ComboHypoToolBase > m_hypoTools {this, "ComboHypoTools", {}, "Tools to perform selection"};
};
#endif // DECISIONHANDLING_COMBOHYPO_H
|
8ec9d3fe0a44ccbb9a303a4ce088582350cc9336 | 62a16006f1a835b081372826957b48b1a9b947a8 | /Compiler/src/implementation/SemanticChecker.cpp | 3d4d42223a377d83aa0242236610174b5d8dea87 | [] | no_license | hilliardj/Klein-Compiler | da0d35716226d13a0d010cf1e835299e1a9bb0bb | a74f8fbd7af198f503ab585d4ec447724ccfc4ae | refs/heads/master | 2021-04-29T09:57:19.349010 | 2017-12-23T22:49:43 | 2017-12-23T22:49:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,344 | cpp | SemanticChecker.cpp | #include "../header/SemanticChecker.h"
#include <string>
#include <tuple>
// Note that most AST nodes hold onto their children in the reverse order by the way
// they are built and put onto the stack.
void SemanticChecker::assignTypeForDefNode(ASTNode& Node) {
assignTypeForBodyNode(*Node.getBodyNode());
assignTypeForTypeNode(*Node.getTypeNode());
if (Node.getTypeNode()->getReturnType() == Node.getBodyNode()->getReturnType())
{
return;
}
else {
Errors.push_back("ERROR: The return type found for " + CurrentFunction + "() does not match its definition");
}
}
void SemanticChecker::assignTypeForTypeNode(ASTNode& Node) {
if (Node.getDataType() == "integer")
{
Node.setReturnType(INTEGER_TYPE);
}
else if (Node.getDataType() == "boolean") {
Node.setReturnType(BOOLEAN_TYPE);
}
}
void SemanticChecker::assignTypeForLessThanNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
ReturnTypes LeftSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode2());
if (RightSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Right side of the < operator is not an integer. Found within - " + CurrentFunction + "()");
}
if (LeftSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Left side of the < operator is not an integer. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(BOOLEAN_TYPE);
}
void SemanticChecker::assignTypeForEqualNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
ReturnTypes LeftSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode2());
if (RightSideType != INTEGER_TYPE && RightSideType != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: Right side of the = operator is not an integer or a boolean. Found within - " + CurrentFunction + "()");
}
if (LeftSideType != INTEGER_TYPE && LeftSideType != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: Left side of the = operator is not an integer or a boolean. Found within - " + CurrentFunction + "()");
}
if (RightSideType != LeftSideType)
{
Errors.push_back("ERROR: Left side of the = operator is of a different type than the right side! Found within - " + CurrentFunction + "()");
}
Node.setReturnType(BOOLEAN_TYPE);
}
void SemanticChecker::assignTypeForBaseExpressionNode(ASTNode& Node)
{
ReturnTypes Type = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
Node.setReturnType(Type);
}
void SemanticChecker::assignTypeForBodyNode(ASTNode& Node) {
vector<ASTNode*> PrintStatements = Node.getPrintStatements();
// Assign types to print statments
for (int i = 0; i < PrintStatements.size(); i++)
{
assignTypeForPrintStatementNode(*PrintStatements[i]);
}
ReturnTypes Type = assignTypeForExpressionNode(*Node.getBaseExprNode());
Node.setReturnType(Type);
}
void SemanticChecker::assignTypeForBaseSimpleExpressionNode(ASTNode& Node)
{
ReturnTypes Type = assignTypeForTermNode(*Node.getBaseTermNode());
Node.setReturnType(Type);
}
void SemanticChecker::assignTypeForAdditionNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForTermNode(*Node.getBaseTermNode());
if (RightSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Right side of the + operator is not an integer. Found within - " + CurrentFunction + "()");
}
ReturnTypes LeftSideType;
if (Node.getBaseSimpleExprNode())
{
LeftSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
}
else {
LeftSideType = assignTypeForTermNode(*Node.getBaseTermNode2());
}
if (LeftSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Left side of the + operator is not an integer. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(INTEGER_TYPE);
}
void SemanticChecker::assignTypeForSubtractionNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForTermNode(*Node.getBaseTermNode());
if (RightSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Right side of the - operator is not an integer. Found within - " + CurrentFunction + "()");
}
ReturnTypes LeftSideType;
if (Node.getBaseSimpleExprNode())
{
LeftSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
}
else {
LeftSideType = assignTypeForTermNode(*Node.getBaseTermNode2());
}
if (LeftSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Left side of the - operator is not an integer. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(INTEGER_TYPE);
}
void SemanticChecker::assignTypeForOrNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForTermNode(*Node.getBaseTermNode());
if (RightSideType != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: Right side of the 'or' operator is not an boolean. Found within - " + CurrentFunction + "()");
}
ReturnTypes LeftSideType;
if (Node.getBaseSimpleExprNode())
{
LeftSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
}
else {
LeftSideType = assignTypeForTermNode(*Node.getBaseTermNode2());
}
if (LeftSideType != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: Left side of the 'or' operator is not a boolean. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(BOOLEAN_TYPE);
}
void SemanticChecker::assignTypeForBaseTermNode(ASTNode& Node)
{
ReturnTypes Type = assignTypeForFactorNode(*Node.getFactorNode());
Node.setReturnType(Type);
}
void SemanticChecker::assignTypeForMultiplicatorNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForFactorNode(*Node.getFactorNode());
if (RightSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Right side of the * operator is not an integer. Found within - " + CurrentFunction + "()");
}
ReturnTypes LeftSideType;
if (Node.getBaseSimpleExprNode())
{
LeftSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
}
else if (Node.getBaseTermNode())
{
LeftSideType = assignTypeForTermNode(*Node.getBaseTermNode());
}
else {
LeftSideType = assignTypeForFactorNode(*Node.getFactorNode2());
}
if (LeftSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Left side of the * operator is not an integer. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(INTEGER_TYPE);
}
void SemanticChecker::assignTypeForDividerNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForFactorNode(*Node.getFactorNode());
if (RightSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Right side of the / operator is not an integer. Found within - " + CurrentFunction + "()");
}
ReturnTypes LeftSideType;
if (Node.getBaseSimpleExprNode())
{
LeftSideType = assignTypeForSimpleExpressionNode(*Node.getBaseSimpleExprNode());
}
else if (Node.getBaseTermNode())
{
LeftSideType = assignTypeForTermNode(*Node.getBaseTermNode());
}
else {
LeftSideType = assignTypeForFactorNode(*Node.getFactorNode2());
}
if (LeftSideType != INTEGER_TYPE)
{
Errors.push_back("ERROR: Left side of the / operator is not an integer. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(INTEGER_TYPE);
}
void SemanticChecker::assignTypeForAndNode(ASTNode& Node)
{
ReturnTypes RightSideType = assignTypeForFactorNode(*Node.getFactorNode());
if (RightSideType != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: Right side of the 'and' operator is not a boolean. Found within - " + CurrentFunction + "()");
}
ReturnTypes LeftSideType;
if (Node.getBaseTermNode())
{
LeftSideType = assignTypeForTermNode(*Node.getBaseTermNode());
}
else {
LeftSideType = assignTypeForFactorNode(*Node.getFactorNode2());
}
if (LeftSideType != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: Left side of the 'and' operator is not a boolean. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(BOOLEAN_TYPE);
}
void SemanticChecker::assignTypeForParenthesisedExpressionNode(ASTNode& Node)
{
ReturnTypes Type = assignTypeForExpressionNode(*Node.getBaseExprNode());
Node.setReturnType(Type);
}
void SemanticChecker::assignTypeForSubtractionFactorNode(ASTNode& Node)
{
ReturnTypes Type = assignTypeForFactorNode(*Node.getFactorNode());
if (Type != INTEGER_TYPE)
{
Errors.push_back("ERROR: You can't apply a negative operator to a non-integer data value. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(INTEGER_TYPE);
}
void SemanticChecker::assignTypeForLiteralFactorNode(ASTNode& Node)
{
ReturnTypes Type = assignTypeForLiteralNode(*Node.getLiteralNode());
Node.setReturnType(Type);
}
void SemanticChecker::assignTypeForFunctionCallNode(ASTNode& Node)
{
string FunctionName = Node.getIdentifierNode()->getIdentifierName();
if (SymbolTable.find(FunctionName) != SymbolTable.end())
{
//There are no parameters in the function call
if (Node.getBaseActualsNode()->getAstNodeType() == BASE_ACTUALS_NODE_TYPE) {
if (!SymbolTable.find(FunctionName)->second.getParameters().empty()) {
Errors.push_back("ERROR: You attempted to call "
+ FunctionName
+ " with no paramaters, but it expects some. Found within - "
+ CurrentFunction + "()");
}
}
//There are parameters in the function call
else {
vector<ASTNode*> FunctionCallParams = Node.getBaseActualsNode()->getNonEmptyActualsNode()->getExpressions();
vector<tuple<string, ReturnTypes>> SymbolTableParams = SymbolTable.find(FunctionName)->second.getParameters();
ReturnTypes type = NO_RETURN_TYPE;
// check Type on each expression used in the function call
if (FunctionCallParams.size() == SymbolTableParams.size()) {
for (int i = FunctionCallParams.size() - 1, j = 0; i >= 0, j < SymbolTableParams.size(); i--, j++) {
type = assignTypeForExpressionNode(*FunctionCallParams.at(i));
if (type == get<1>(SymbolTableParams.at(j))) {
continue;
}
else
{
// param doesn't match the expected Type
Errors.push_back("ERROR: There was a type mismatch when calling function "
+ FunctionName
+ "(). Found within - "
+ CurrentFunction + "()");
continue;
}
}
}
else
{
Errors.push_back("ERROR: You attempted to call "
+ FunctionName + "() with a mismatching number of arguments. This function expects "
+ to_string(SymbolTableParams.size())
+ " parameter(s). Found within - " + CurrentFunction + "()");
}
}
// set this expression node Type to that of the function call.
// Also put the CurrentFunction into the called functions list.
SymbolTable.find(FunctionName)->second.addFunctionCallers(CurrentFunction);
Node.setReturnType(SymbolTable.find(FunctionName)->second.getReturnType());
}
else {
Errors.push_back("ERROR: Call to function "
+ FunctionName
+ "(), but the Function does not exist. Found within - "
+ CurrentFunction + "()");
// Still need to assign types to paramaters in order to see if any variables are used
vector<ASTNode*> FunctionCallParams = Node.getBaseActualsNode()->getNonEmptyActualsNode()->getExpressions();
for (int i = FunctionCallParams.size() - 1; i >= 0; i--) {
assignTypeForExpressionNode(*FunctionCallParams.at(i));
}
}
}
void SemanticChecker::assignTypeForSingletonIdentifierFactorNode(ASTNode& Node)
{
assignTypeForIdentifierNode(*Node.getIdentifierNode());
Node.setReturnType(Node.getIdentifierNode()->getReturnType());
}
void SemanticChecker::assignTypeForNotFactorNode(ASTNode& Node)
{
ReturnTypes Type = assignTypeForFactorNode(*Node.getFactorNode());
if (Type != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: You can't apply the 'not' operation to a non-boolean data type. Found within - " + CurrentFunction + "()");
}
Node.setReturnType(BOOLEAN_TYPE);
}
void SemanticChecker::assignTypeForIfFactorNode(ASTNode& Node)
{
ReturnTypes ElseType = assignTypeForExpressionNode(*Node.getBaseExprNode());
ReturnTypes ThenType = assignTypeForExpressionNode(*Node.getBaseExprNode2());
ReturnTypes IfCheck = assignTypeForExpressionNode(*Node.getBaseExprNode3());
if (IfCheck != BOOLEAN_TYPE)
{
Errors.push_back("ERROR: If statement condition needs to be of type boolean. Found within - " + CurrentFunction + "()");
}
if (ThenType == ElseType)
{
Node.setReturnType(ThenType);
}
else {
Node.setReturnType(OR_TYPE);
}
}
void SemanticChecker::assignTypeForIdentifierNode(ASTNode& Node)
{
vector<tuple<string, ReturnTypes>> SymbolTableParams = SymbolTable.find(CurrentFunction)->second.getParameters();
ReturnTypes Type = NO_RETURN_TYPE;
for (int i = 0; i < SymbolTableParams.size(); i++) {
if (Node.getIdentifierName() == get<0>(SymbolTableParams.at(i))) {
//add variable to used variable list and assign Type to it
SymbolTable.find(CurrentFunction)->second.variableUsed(Node.getIdentifierName());
Type = get<1>(SymbolTableParams.at(i));
break;
}
}
if (Type == NO_RETURN_TYPE)
{
Errors.push_back("ERROR: Variable '"
+ Node.getIdentifierName()
+ "' has not been declared. Found within - "
+ CurrentFunction + "()");
}
Node.setReturnType(Type);
}
void SemanticChecker::assignTypeForIntegerLiteralNode(ASTNode& Node)
{
Node.setReturnType(INTEGER_TYPE);
}
void SemanticChecker::assignTypeForBooleanLiteralNode(ASTNode& Node)
{
Node.setReturnType(BOOLEAN_TYPE);
}
void SemanticChecker::assignTypeForPrintStatementNode(ASTNode& Node)
{
assignTypeForExpressionNode(*Node.getBaseExprNode());
SymbolTable.find("print")->second.addFunctionCallers(CurrentFunction);
Node.setReturnType(NO_RETURN_TYPE);
}
// helper methods -------------------------------------------------------
ReturnTypes SemanticChecker::assignTypeForExpressionNode(ASTNode& Node) {
if (Node.getAstNodeType() == BASE_EXPR_NODE_TYPE)
{
assignTypeForBaseExpressionNode(Node);
return Node.getReturnType();
}
else if (Node.getAstNodeType() == LESS_THAN_EXPR_NODE_TYPE)
{
assignTypeForLessThanNode(Node);
return BOOLEAN_TYPE;
}
else {
assignTypeForEqualNode(Node);
return BOOLEAN_TYPE;
}
}
ReturnTypes SemanticChecker::assignTypeForSimpleExpressionNode(ASTNode& Node) {
if (Node.getAstNodeType() == BASE_SIMPLE_EXPR_NODE_TYPE)
{
assignTypeForBaseSimpleExpressionNode(Node);
return Node.getReturnType();
}
else if (Node.getAstNodeType() == ADDITION_SIMPLE_EXPR_NODE_TYPE)
{
assignTypeForAdditionNode(Node);
return INTEGER_TYPE;
}
else if (Node.getAstNodeType() == SUBTRACTOR_SIMPLE_EXPR_NODE_TYPE)
{
assignTypeForSubtractionNode(Node);
return INTEGER_TYPE;
}
else {
assignTypeForOrNode(Node);
return BOOLEAN_TYPE;
}
}
ReturnTypes SemanticChecker::assignTypeForTermNode(ASTNode& Node)
{
if (Node.getAstNodeType() == BASE_TERM_NODE_TYPE)
{
assignTypeForBaseTermNode(Node);
return Node.getReturnType();
}
else if (Node.getAstNodeType() == MULTIPLICATOR_TERM_NODE_TYPE)
{
assignTypeForMultiplicatorNode(Node);
return INTEGER_TYPE;
}
else if (Node.getAstNodeType() == DIVIDER_TERM_NODE_TYPE)
{
assignTypeForDividerNode(Node);
return INTEGER_TYPE;
}
else {
assignTypeForAndNode(Node);
return BOOLEAN_TYPE;
}
}
ReturnTypes SemanticChecker::assignTypeForFactorNode(ASTNode& Node)
{
if (Node.getAstNodeType() == PARENTHESISED_EXPR_FACTOR_NODE_TYPE)
{
assignTypeForParenthesisedExpressionNode(Node);
return Node.getReturnType();
}
else if (Node.getAstNodeType() == SUBTRACTION_FACTOR_NODE_TYPE)
{
assignTypeForSubtractionFactorNode(Node);
return INTEGER_TYPE;
}
else if (Node.getAstNodeType() == LITERAL_FACTOR_NODE_TYPE)
{
assignTypeForLiteralFactorNode(Node);
return Node.getReturnType();
}
else if (Node.getAstNodeType() == FUNCTION_CALL_TYPE)
{
assignTypeForFunctionCallNode(Node);
return Node.getReturnType();
}
else if (Node.getAstNodeType() == SINGLETON_IDENTIFIER_FACTOR_NODE_TYPE)
{
assignTypeForSingletonIdentifierFactorNode(Node);
return Node.getReturnType();
}
else if (Node.getAstNodeType() == NOT_FACTOR_NODE_TYPE)
{
assignTypeForNotFactorNode(Node);
return BOOLEAN_TYPE;
}
else {
assignTypeForIfFactorNode(Node);
// not a boolean because it could be an OR Type
return Node.getReturnType();
}
}
ReturnTypes SemanticChecker::assignTypeForLiteralNode(ASTNode& Node)
{
if (Node.getAstNodeType() == INTEGER_LITERAL_NODE_TYPE)
{
assignTypeForIntegerLiteralNode(Node);
return INTEGER_TYPE;
}
else {
assignTypeForBooleanLiteralNode(Node);
return BOOLEAN_TYPE;
}
} |
e2bd2a07d2b928686a86242c70f79f1b2278ba32 | 6817ea7e9e59fc702de5291c6691153de9f3acc2 | /leetcode/lowestcommonAncestor.cpp | 7cc8dcb4c597b076b3f4d659611d1e304f08803a | [] | no_license | coolnut12138/OJ | 7b3cec2340a0913105f4f85efb72ba538618fddc | e4144c7b4246d7e0921bd8e214e7fb93452457aa | refs/heads/master | 2020-05-05T10:45:47.959641 | 2019-09-21T15:25:04 | 2019-09-21T15:25:04 | 179,959,652 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,612 | cpp | lowestcommonAncestor.cpp | //leetcode 236,两个结点最近的公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr || root == p || root == q)
return root;
TreeNode* leftN = lowestCommonAncestor(root->left, p, q);
TreeNode* rightN = lowestCommonAncestor(root->right, p, q);
if (leftN != nullptr && rightN != nullptr)
return root;
if (leftN == nullptr)
return rightN;
return leftN;
}
};
//再写一个函数比较好理解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//判断结点是否在这个子树
bool contains(TreeNode* root, TreeNode* node){
if (root == nullptr){
return false;
}
if (root == node){
return true;
}
if (contains(root->left, node) == true){
return true;
}
return contains(root->right, node);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
bool pInleft = contains(root->left, p);
bool qInleft = contains(root->left, q);
bool pInright = !pInleft && p != root;
bool qInright = !qInleft && q != root;
if (pInleft && qInleft){
return lowestCommonAncestor(root->left, p, q);
}
if (pInright && qInright){
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
}; |
d67c9c657c265e4c6e225d1747ba03615a07da5e | e7023460e28d3a95c347fe4eb06698c188d743f2 | /Sticky/native/StickEd/StickEd.cpp | f6bca5cf48b777400462a35c4e8598357d40af8c | [
"MIT"
] | permissive | madskristensen/blog | 1c32023c9ac15076d28a58aa544da5c331d758ff | d2c4ce2bb1da4186c7c3916e50641066569e97bf | refs/heads/master | 2021-01-14T12:36:04.364541 | 2016-04-05T16:27:32 | 2016-04-05T16:27:32 | 55,522,854 | 1 | 0 | null | 2016-04-05T16:12:14 | 2016-04-05T16:12:13 | null | UTF-8 | C++ | false | false | 347,550 | cpp | StickEd.cpp | #include <windows.h>
#include <wtypes.h>
#include <shellapi.h>
#include <commdlg.h>
#include <commctrl.h>
#include <mmsystem.h>
#pragma warning( push )
#pragma warning( disable: 4786 4702 )
#include <string>
#include <vector>
#include <list>
#include <map>
#include <algorithm>
using namespace std;
#pragma warning( pop )
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#pragma warning( push )
#pragma warning( disable: 4201 )
#include <vfw.h>
#pragma warning( pop )
#include "avi_utils.h"
#include "../zip.h"
#include "../unzip.h"
#include "../regex.h"
#pragma hdrstop // precompiled headers end here
#include "../body.h"
#include "../utils.h"
#include "resource.h"
//---------------------------------------------------------------------------
#ifdef __BORLANDC__
#include <float.h>
#include <condefs.h>
USEUNIT("..\regex.cpp");
USEUNIT("..\body.cpp");
USEUNIT("..\utils.cpp");
USEUNIT("..\unzip.cpp");
USEUNIT("avi_utils.cpp");
USERC("edres.rc");
USEUNIT("..\zip.cpp");
//---------------------------------------------------------------------------
#pragma warn -8080
#endif
//---------------------------------------------------------------------------
#include <sys/stat.h>
using namespace stk;
HINSTANCE hInstance;
UINT StickClipboardFormat;
unsigned char *sampledat[3]={0,0,0}; unsigned int samplesize[3];
HWND hwnd_acc=0; HACCEL hac;
COLORREF CREF(stk::RGBCOLOR rgb)
{
return RGB(rgb.r, rgb.g, rgb.b);
}
void stk::luassertmsg(const char *s,const char *msg,const char *f,unsigned int l)
{ char c[2000]; wsprintf(c,"%s '%s'\r\n%s : %u",msg,s,f,l);
MessageBox(hwnd_acc,c,"Assertion failed",MB_OK);
}
string reggarble(const string s,bool emptyiswildcard=false);
double myatan2(double dy,double dx) {if (dy==0) {if (dx<0) return pi; else return 0;} else return atan2(dy,dx);}
int CCW(POINT p0,POINT p1,POINT p2) {return ((p1.x-p0.x)*(p2.y-p0.y) > (p1.y-p0.y)*(p2.x-p0.x)) ? 1 : -1;}
bool intersects(POINT p1, POINT p2, POINT p3, POINT p4) {return (((CCW(p1,p2,p3)*CCW(p1,p2,p4))<=0) && ((CCW(p3,p4,p1)*CCW(p3,p4,p2)<=0)));}
bool inpoly(POINT *pts, int npts, POINT p, RECT &brc) // assumes a closed poly
{ if (p.x<brc.left || p.x>brc.right || p.y<brc.top || p.y>brc.bottom) return false;
POINT poutside=p; poutside.x=brc.right+50; int nints=0;
for (int i=0; i<npts-1; i++) {if (intersects(p,poutside, pts[i],pts[i+1])) nints++;}
return (nints&1);
}
void PumpMessages()
{ MSG msg; for (;;)
{ BOOL res=PeekMessage(&msg,0,0,0,PM_REMOVE);
if (!res||msg.message==WM_QUIT) return;
if (!TranslateAccelerator(hwnd_acc,hac,&msg))
{ TranslateMessage(&msg); DispatchMessage(&msg);
}
}
}
string StringAng(double a) {string s=""; if (a<0) {a=-a; s="-";} char c[20]; sprintf(c,"%.1lf",a*180.0/pi); return s+c+"deg";}
string StringLength(double m) {char c[20]; sprintf(c,"%.2lf",m); return string(c)+"cm";}
string StringFrac(double f) {char c[20]; sprintf(c,"%.2lf",f); return string(c)+"%";}
string StringNiceFloat(double d)
{ char c[100]; sprintf(c,"%.3lf",d); int len=strlen(c);
if (len>1 && c[len-1]=='0') {c[len-1]=0; len--;}
if (len>1 && c[len-1]=='0') {c[len-1]=0; len--;}
if (len>1 && c[len-1]=='0') {c[len-1]=0; len--;}
if (len>1 && c[len-1]=='.') {c[len-1]=0;}
return string(c);
}
//
const int ArmLength=20;
const int ArmSpotLength = 3;
const int PieLength=10;
const int SelPieLength=20;
const int SpotLength=4;
const int PlusLength=8;
const int PlusOffLength=5;
const int SelThickLength=2;
const int AnchorLength=20;
const int AnchorOffLength=6;
const int AnchorMargin=10;
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
// -1=htMiss 0=spot, 1=plus, 2=amin, 3=amax, 4=line, 5=root, 6=pie, 7=shape
enum THitType {htMiss,htSpot,htPlus,htAmin,htAmax,htLine,htRoot,htPie,htShape,htAroot};
// 0=none 1=create, 2=edit, 3=zoom
enum TTool {tNone,tCreate,tEdit,tZoom};
// 0=nothing, 1=button down on a node, 2=dragging to create new line, 3=moving an existing node
// 4=dragging aoff, 5=dragging ascale, 6=animating, 7=zoom-rubberbanding, ...
enum TMode {mNothing,mNodePressing,mCreateDragging,mNodeMoving,mAoffDragging,
mAscaleDragging,mLminDragging,mLmaxDragging,mNothingTesting,mZoomDragging,
mSelDragging,
mShapeLinePressing,mShapeSpotPressing,mCreateCornerDragging,mCornerMoving,mExporting};
enum TSetSubject {tsLine,tsFill,tsLineFill,tsFreq,tsWhatever};
typedef struct {int r,g,b;} COL; int ncols=7;
COL defcols[7]={{0,0,0}, {255,255,255}, {255,20,10},{30,245,20},{30,20,225},{200,200,10},{200,10,200}};
enum TColIndex {cBlack, cWhite, cRed, cGreen, cBlue, cYellow, cPurple};
typedef struct {COL c; string name;} TUserColour; list<TUserColour> usercols;
typedef struct {double r; bool reflect; string name;} TUserCum; list<TUserCum> usercums;
list<double> userthick;
bool UserSnap, UserGrid, WhitePrint;
bool ShowAngles, ShowJoints, ShowInvisibles;
COLORREF UserBmpBackground; bool UserCheckUpright;
//
string exportfn; // name of the .avi
bool exportproc; // export a procession? or just the current stick?
string exportfigs;// the procession
int exporttune; // 0=dancing 1=thrashing 2=to a WAV file
string exportwav;// the wav file
int exportw,exporth; // dimensions of exported video
bool exporttimefixed;// is it a fixed time? or the duration of the wav file?
int exporttime; // in milliseconds.
int exportproctime; // milliseconds each figure is on stage
int exportfps; // frames per second
bool exportcompress; DWORD exportopt; // show the compression dialog? and its fourCC, or 0 if empty
vector<TPre> exportpre; // just an internal cache we use
//
typedef struct {string fn,back;} TUserBack; list<TUserBack> UserBacks;
void RegLoadUser(); void RegSaveUser();
int ParseUserCols(const char *); unsigned int WriteUserCols(char *buf,unsigned int buflen);
int ParseUserCums(const char *); unsigned int WriteUserCums(char *buf,unsigned int buflen);
int ParseUserThicks(const char*);unsigned int WriteUserThicks(char *buf,unsigned int buflen);
int ParseUserBacks(const char*); unsigned int WriteUserBacks(char *buf,unsigned int buflen);
typedef struct
{ int s; // shape index. Either this will be to a real shape, or to the "limbs" shape, or -1
int n; // limb index. For a limb, this will be its index. Or -1.
THitType type; // limbs use all fields here, shapes use only htLine or htShape or htSpot, misses are htMiss
int si; double sf; // for a shape/htLine, user clicked on the line starting at index si, fraction sf of the way through
} THitTest;
typedef struct
{ double screenang, screenrad;
double relang, relrad;
double f;
bool isin;
} TAdjAngle;
class TUndoData
{ public:
TUndoData() : buf(0), len(0), sbuf(0), slen(0) {}
void releasebmps() {for (list<TBmp>::iterator bi=bmps.begin(); bi!=bmps.end(); bi++) bi->release(); bmps.clear();}
char *buf; unsigned int len;
char *sbuf; unsigned int slen;
list<TBmp> bmps;
list<int> sellimbs, selshapes;
};
// An UndoData may be hanging around in the the free-stack, or the used-stack.
// In both cases, its 'buf' is kept around. That's so we can just reuse
// some already-allocated memory.
// However, the bmps array is only used for certain undo-points, and must
// be empty in other undo-points and on the free-stack. The bmps array contains
// its own private buffes, and all its hbms are 0.
typedef struct {double min[6], max[6], l[6], r[6];} TSpot;
// a TSpot is a sample that we get from analyzing a wav file, and fourier-transforming
// it, in preparation for exporting sticks to AVI that are dancing to the wav
class TEditor
{ public:
TEditor();
~TEditor();
bool isready;
bool ExportCancelled,ExportTerminated; // reset at start of FileExport. Is set by various cancel buttons.
HWND mhwnd,chwnd; HWND hstatwnd;
HBITMAP hbackdrop; string fnbackdrop;
TBody *body;
TLimb rubber; // where the creating- or dragging-rubber band is
TJointRef rubend; // -1 if the rubber band ends in mid-air, i if it ends on a spot (i.e. creating a shape)
int cori; // if we have corner-creating rubber bands, it comes on hit.s.p[] between cori,cori+1
double corx,cory; // corx,y are the body-coords of the target of the rubber band
TJointRef cortarget,corotarget; // cortarget is the spot index where we've landed. Otarget is for dragging, where it was before we dragged it. Cori=-1,cortarget=-1 for none.
TMode mode; THitTest hit; // this hit is the thing that's currently selected
list<int> sellimbs, selshapes; bool numsel; // additionally, for multiple selection, I've added these lists
void IncNextChan(); int nextchan, nextband; // these are the channel and band for the next one to be created
string nextlinestyle,nextfillstyle,nextfreqstyle;
TTool tool;
int zoomx0,zoomy0,zoomx,zoomy;
// the zoomcords and time are used to draw rubberbanding both for zoom-in and for multi-select
THitTest LastHover, ThisHover; bool IsHoverTimer; unsigned int EndHoverTimer;
void Redraw() {InvalidateRect(chwnd,NULL,FALSE);}
//{HDC hdc=GetDC(chwnd); Draw(hdc); ReleaseDC(chwnd,hdc);}
HDC memDC; HBITMAP memBM,oldBM; int width,height; // (temp) the hdc-coordinates where we'll drawing
void Size(int width,int height);
void Recalc(int n);
bool Draw(HDC hdc,string *err=0);
void DrawPie(HDC hdc,TLimb &dst,int length,bool fillall);
void DrawPiePart(HDC hdc,int x0,int y0,double length,double ang0,double ang,double ang1);
void DrawLinePart(HDC hdc,double thick,double ang,int x0,int y0,int x1,int y1,int x2,int y2);
double zoom, offx, offy; // screenpos = (point+off)*scale+midwin
void Scale(double x,double y, int *sx,int *sy);
void Unscale(int x,int y, double *sx,double *sy);
int b2x(double x); int b2y(double y);
double x2b(int x); double y2b(int y);
int circlelimb_from_shape(int shape); // if this shape is a circle-only fill, return circle index, otherwise -1.
int circleshape_from_limb(int limb);
THitTest PointAtCoords(int x,int y,bool isrightclick);
void ObjectsInRect(double x0,double y0,double x1,double y1,list<int> &limbs,list<int> &shapes);
void ShowHitTest();
TAdjAngle AngleFromOff(double dx,double dy,double ang0,double aoff,double ascale);
TAdjAngle AngleNearbyFromOff(double dx,double dy,double ang0,double ascreenprev);
double SnapAngle(double ang,bool clampzero);
bool SnapToGrid(int *x,int *y);
void ButtonDown(int x,int y);
void SelectWobble(int x,int y); // when the button is down to select and the mouse has moved marginally
void SelectShapeLineWobble(int x,int y); // similarly, but when the button was down on a shape's line
void SelectShapeSpotWobble(int x,int y); // similarly, but when the button was donw on a shape's spot
void CreatingMove(int x,int y); // when we're rubber-banding and the mouse moves
void CornerMove(int x,int y); // when we're rubber-banding a new or existing corner and the mouse moves
void RepositioningMove(int i,int x,int y,bool suppresscalcdraw=false); // when we're moving an existing node
void AngleMove(int x,int y); // when we're moving an angle handle
void SpringMove(int x,int y); // when we're moving a spring handle
void RubberMove(int x,int y); // when we're rubber-banding
void Unselect(); // when the mouse lets go after selecting a thing
void FinishCreate(); // when the mouse lets go after drag-creating a thing
void FinishCreateCorner(); // same, but for creating a corner
void FinishRepositioning(); // when the mouse lets go after repositioning a node
void FinishAngling(); // when we finish angling
void FinishSpringing(); // when we finish springing
void FinishZooming(); // when we finish rubberband-zooming
void FinishSeling(); // when we finish rubberband-selecting
void RightClick(int x,int y);
void ShapeClick(int x,int y,THitTest &ht); // for right-clicking on a shape
void BackgroundClick(int x,int y);
void HoverMonitor(int x,int y);
void LazyCreateCircleShapes(); // create fills inside circles if an op was applied to them implied
void Backdrop(const string fn,bool suppressredraw=false);
void DeleteLimbOrShape(); void InsertLimb();
bool Copy(); void Paste(); void Cut();
void Flip();
void Stretch(int dir); void RecStretch(int n,double scale);
void SetChanBand(int c,int b);
void SetCum(double c,int reflect);
void SetAnchor(int anch);
void ToggleLineType(); void SetVisibility(TSetSubject subj,int newv);
void ToggleNegative(); void SetAlternate(int newa);
void SetCol(TSetSubject subj,TColIndex i); void SetCol(TSetSubject subj,int r,int g,int b);
void SetThickness(double w);
void SetEffect(TSetSubject subj,const string effect);
void SetStyle(TSetSubject subj, int index);
void SetStyle(char shortcutkey);
void SetF(int node, int chan,int band, double f,bool suppresscalcdraw=false);
void SetOrder(int dir);
void SetBitmap(const string bn);
void Cursor(int dir);
void Zoom(int dir);
void GetRootLimbsOfSellimbs(list<int> *roots); // a collection of all the roots from limbs
bool GetRootLimbsOfSelection(list<int> *roots); // from all shapes
void SetScrollBars();
void Scroll(bool horiz,int code,int pos);
double s_bleft,s_bright,s_btop,s_bbottom; // we keep these, to re-use them (only) while
double s_fleft,s_fright,s_ftop,s_fbottom; // the user does a thumb-track
void UserColours(HWND hpar); void UserThicknesses(HWND hpar); void Bitmaps(HWND hpar);
void UserCumulatives(HWND hpar);
string AddBitmap(const char *fn);
void DeleteBitmap(const string zname);
string RenameBitmap(const string oldzn,const string newzn);
string CleanBitmapName(const string s);
void Effects(HWND hpar);
string CleanEffectName(const string s);
string EffectClick(HWND hpar,const string s);
void Styles(HWND hpar);
string CleanStyleName(const string s);
string StyleClick(HWND hpar,const string s);
void ApplyStyle(const string name,bool suppressredraw=false);
TStyle StyleFromName(const string name);
void Category();
void TargetFramerate();
void EditUndo(); void EditRedo(); void MarkUndo(bool withbitmaps=false);
list<TUndoData> undos; int undopos; // we normally sit at '0', the front of the undos list
list<TUndoData> frees; // free buffers for storing undo positions
void DebugPaint(HDC hdc,RECT &rc);
void FileOpen(char *fn);
bool FileSave();
bool FileSaveAs(char *fn);
void FileExport(); int fft(WavChunk *wav, TSpot *spots, int spotsize);
void FileNew(); void FileReady();
bool FileClose();
bool MaybeCheckUpright(bool forcedialog=false); void FixUpright();
char curfile[MAX_PATH]; bool ismodified;
void ShowTitle(); void ShowHint(string s); void SetCursor(); void UpdateMenus();
HCURSOR hCursor[8]; // 1=move 2=absrel 3=angle 4=smallcreate 5=bigcreate 6=zoom 7=pointer
void Invert();
void Animate();
void Tick(bool atend);
void StopAnimate();
int idTimer;
unsigned int timeStart, timePrev;
int samplei;
};
TEditor::TEditor()
{ isready=false;
chwnd=0; mhwnd=0;
memDC=CreateCompatibleDC(NULL);
memBM = CreateCompatibleBitmap(memDC,100,100);
oldBM = (HBITMAP)SelectObject(memDC,memBM);
hbackdrop=0; fnbackdrop="";
idTimer=0;
tool=tCreate;
ismodified=false;
hit.s=-1; hit.n=-1; hit.type=htMiss; rubend.i=-1; cori=-1; sellimbs.clear(); selshapes.clear();
LastHover.n=-1; LastHover.type=htMiss; ThisHover.n=-1; ThisHover.type=htMiss; IsHoverTimer=false;
hCursor[1]=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_MOVE));
hCursor[2]=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_ABSREL));
hCursor[3]=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_ANGLE));
hCursor[4]=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_SMALLCREATE));
hCursor[5]=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_BIGCREATE));
hCursor[6]=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_ZOOM));
hCursor[7]=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_POINTER));
body=new TBody();
undos.clear(); undopos=-1;
//
}
TEditor::~TEditor()
{ SelectObject(memDC,oldBM);
DeleteObject(memDC); memDC=NULL;
DeleteObject(memBM); memBM=NULL;
if (hbackdrop!=0) DeleteObject(hbackdrop); hbackdrop=0; fnbackdrop="";
if (body!=NULL) delete body; body=NULL;
for (list<TUndoData>::iterator i=undos.begin(); i!=undos.end(); i++)
{ if (i->buf!=0) delete[] i->buf; i->buf=0;
if (i->sbuf!=0) delete[] i->sbuf; i->sbuf=0;
i->releasebmps();
}
undos.clear();
for (list<TUndoData>::iterator i=frees.begin(); i!=frees.end(); i++)
{ if (i->buf!=0) delete[] i->buf; i->buf=0;
if (i->sbuf!=0) delete[] i->sbuf; i->sbuf=0;
LUASSERT(i->bmps.size()==0);
}
frees.clear();
undopos=-1;
}
void TEditor::EditUndo()
{ int newundopos=undopos+1;
TUndoData ud; ud.buf=0; int i=0;
if (undopos==-1)
{ if (undos.size()>0) ud=undos.front();
}
else
{ for (list<TUndoData>::const_iterator it=undos.begin(); it!=undos.end() && i<=newundopos+1; it++,i++)
{ ud=*it;
}
}
if (ud.buf==0) return; // trying to undo but we don't have a history that far back
// if we weren't already in an undo, we have to save ourselves
// Moreover, if the top of the undostack had different bitmaps, we have to save our
// own bitmaps.
if (undopos==-1)
{ MarkUndo(ud.bmps.size()>0);
}
undopos=newundopos;
//
char err[1000];
body->ReadData(ud.buf,err,rdOverwrite,NULL);
//
StylesFromString(ud.sbuf,body->styles);
//
if (ud.bmps.size()>0)
{ for (vector<TBmp>::iterator i=body->bmps.begin(); i!=body->bmps.end(); i++) i->release();
body->bmps.clear();
for (list<TBmp>::const_iterator i=ud.bmps.begin(); i!=ud.bmps.end(); i++)
{ TBmp b; b.name=i->name; b.bufsize=i->bufsize; b.buf=new char[b.bufsize]; memcpy(b.buf,i->buf,b.bufsize);
PrepareBitmapData(&b,true); body->bmps.push_back(b);
}
}
body->MakeChildren();
MakeBindexes(body); MakeEindexes(body);
sellimbs=ud.sellimbs; selshapes=ud.selshapes; hit.n=-1; hit.s=-1; hit.type=htMiss;
Recalc(0);
Redraw(); SetCursor();
UpdateMenus();
}
void TEditor::EditRedo()
{ if (undopos==-1) return;
undopos--;
TUndoData ud; ud.buf=0; int i=0;
// undopos=-1: front
// undopos=0: first
for (list<TUndoData>::const_iterator it=undos.begin(); it!=undos.end() && i<=undopos+1; it++,i++)
{ ud=*it;
}
if (ud.buf==0) return;
char err[1000];
body->ReadData(ud.buf,err,rdOverwrite,NULL);
//
StylesFromString(ud.sbuf,body->styles);
//
sellimbs=ud.sellimbs; selshapes=ud.selshapes; hit.n=-1; hit.s=-1; hit.type=htMiss;
if (ud.bmps.size()>0)
{ for (vector<TBmp>::iterator i=body->bmps.begin(); i!=body->bmps.end(); i++) i->release();
body->bmps.clear();
for (list<TBmp>::const_iterator i=ud.bmps.begin(); i!=ud.bmps.end(); i++)
{ TBmp b; b.name=i->name; b.bufsize=i->bufsize; b.buf=new char[b.bufsize]; memcpy(b.buf,i->buf,b.bufsize);
PrepareBitmapData(&b,true); body->bmps.push_back(b);
}
}
body->MakeChildren();
MakeBindexes(body); MakeEindexes(body);
Recalc(0);
Redraw(); SetCursor();
if (undopos==-1) {TUndoData ud=undos.front(); undos.pop_front(); ud.releasebmps(); frees.push_back(ud);}
// tricky, that line just above!
// the undo queue doesn't store the current position (unless we're inside an undo-redo detour)
// so, when we finish that detour, we have to remove it.
UpdateMenus();
}
void TEditor::MarkUndo(bool withbitmaps)
{ // first, if there were any 'redos' pending, we'll forget them
bool inmiddle=false;
while (undopos>-1)
{ inmiddle=true;
TUndoData ud=undos.front(); undos.pop_front(); ud.releasebmps(); frees.push_back(ud); undopos--;
}
if (inmiddle) {TUndoData ud=undos.front(); undos.pop_front(); ud.releasebmps(); frees.push_back(ud);}
// next, if we'd reached the limit, forget the oldest one
while (undos.size()>=5)
{ TUndoData ud=undos.back(); undos.pop_back(); ud.releasebmps(); frees.push_back(ud);
}
// now, either reuse an old buffer, or create a new one.
TUndoData ud; ud.buf=0; if (frees.size()>0) {ud=frees.back(); frees.pop_back();}
LUASSERT(ud.bmps.size()==0);
if (ud.buf==0) ud.buf=new char[10000]; ud.len=10000;
if (ud.sbuf==0) ud.sbuf=new char[1000]; ud.slen=1000;
ud.sellimbs=sellimbs; ud.selshapes=selshapes;
// save our current state in there
unsigned int wlen = body->WriteData(ud.buf,ud.len,0);
if (wlen>ud.len)
{ delete[] ud.buf; ud.buf = new char[wlen*2]; ud.len=wlen*2;
body->WriteData(ud.buf,ud.len,0);
}
//
unsigned int slen = StylesToString(ud.sbuf,ud.slen,body->styles);
if (slen>ud.slen) {delete[] ud.sbuf; ud.slen=slen*2; ud.sbuf=new char[ud.slen]; StylesToString(ud.sbuf,ud.slen,body->styles);}
//
if (withbitmaps)
{ for (vector<TBmp>::const_iterator bi=body->bmps.begin(); bi!=body->bmps.end(); bi++)
{ TBmp b; b.name=bi->name; b.bufsize=bi->bufsize;
b.buf=new char[b.bufsize]; memcpy(b.buf,bi->buf,b.bufsize);
ud.bmps.push_back(b);
}
}
undos.push_front(ud);
UpdateMenus();
}
int dbp(HDC hdc,int y,int,const string s)
{ TextOut(hdc,0,y,s.c_str(),s.length());
return y+16;
}
void TEditor::DebugPaint(HDC hdc,RECT &rc)
{ int y=0; int w=rc.right-rc.left; int c=0;
if (undopos==-1) y=dbp(hdc,y,w,"*");
for (list<TUndoData>::const_iterator i=undos.begin(); i!=undos.end(); i++,c++)
{ unsigned char *buf = (unsigned char*)i->buf;
string s=""; s.resize(20);
for (int j=0; j<20; j++)
{ unsigned char c=buf[j];
if (c>=32 && c<=127) s[j]=c; else if (c==0) s[j]='0'; else s[j]='.';
}
s[19]=0;
y=dbp(hdc,y,w,s);
if (undopos==c) y=dbp(hdc,y,w,"*");
}
}
int TEditor::circlelimb_from_shape(int shape)
{ stk::TShape &s = body->shapes[shape];
if (s.p.size()!=2) return -1;
if (s.p[0].i!=s.p[1].i) return -1;
if (s.p[0].ar==s.p[1].ar) return -1;
int i=s.p[0].i;
if (body->limbs[i].type!=3) return -1;
return i;
}
int TEditor::circleshape_from_limb(int nlimb)
{ TLimb &limb = body->limbs[nlimb];
if (limb.type!=3) return -1;
for (int i=0; i<(int)body->shapes.size(); i++)
{ stk::TShape &shape = body->shapes[i];
if (shape.p.size()==2 && shape.p[0].i==nlimb && shape.p[1].i==nlimb && shape.p[0].ar!=shape.p[1].ar) return i;
}
return -1;
}
// We assume that the x,y given to us are relative to the origin (i.e. to limb 0)
void TEditor::Scale(double x,double y,int *sx,int *sy)
{ x+=offx; y+=offy;
x*=zoom; y*=zoom;
*sx=width/2+(int)x; *sy=height/2+(int)y;
}
int TEditor::b2x(double x) {x+=offx; if (mode==mNothingTesting) x+=body->anchx; x*=zoom; return width/2+(int)x;}
int TEditor::b2y(double y) {y+=offy; if (mode==mNothingTesting) y+=body->anchy; y*=zoom; return height/2+(int)y;}
int gb2x(void *dat,double x) {TEditor *e=(TEditor*)(dat); if (e==0) return 0; return e->b2x(x);}
int gb2y(void *dat,double y) {TEditor *e=(TEditor*)(dat); if (e==0) return 0; return e->b2y(y);}
void TEditor::Unscale(int sx,int sy, double *x,double *y)
{ sx=sx-width/2; sy=sy-height/2;
*x=((double)sx)/zoom-offx; *y=((double)sy)/zoom-offy;
}
double TEditor::x2b(int x)
{ double d=x-width/2;
d/=zoom;
d-=offx;
if (mode==mNothingTesting) d-=body->anchx;
return d;
}
double TEditor::y2b(int y) {double d=y-height/2; d/=zoom; d-=offy; if (mode==mNothingTesting) d-=body->anchy; return d;}
// Given dx,dy, and a line whose calculated aoff is ang0 (allows us to calculate parent's bias)
// and whose parameters are aoff and ascale, figure out the angle to this point
// Returns whether or not is inside.
TAdjAngle TEditor::AngleFromOff(double dx,double dy,double ang0,double aoff,double ascale)
{ TAdjAngle aa;
double bias=ang0-aoff;
double ang=myatan2(dy,dx); aa.screenang=ang;
double r=sqrt((double)(dx*dx+dy*dy)); aa.screenrad=r*zoom;
ang=ang-bias; // now ang is in the same league as aoff and ascale.
// Next: if ascale was negative, we'll put ang negative of aoff;
// if ascale was positive, we'll put ang positive of aoff.
if (ascale<0) {while (ang<aoff) ang+=2*pi; while (ang>aoff) ang-=2*pi;}
else if (ascale>0) {while (ang>aoff) ang-=2*pi; while (ang<aoff) ang+=2*pi;}
else // if ascale was zero then we're doing something different: finding the angle that's close to what it was before
{
}
aa.relang=ang;
aa.relrad=r;
// The question now is merely: is the angle inside the range?
if (ascale==0) {aa.f=0; aa.isin=true;}
else {aa.f=(ang-aoff)/ascale; aa.isin = (aa.f>=0 && aa.f<=1);}
//
return aa;
}
TAdjAngle TEditor::AngleNearbyFromOff(double dx,double dy,double ang0,double ascreenprev)
{ TAdjAngle aa;
if (ascreenprev<-4*pi || ascreenprev>4*pi) ascreenprev=0;
double bias=ang0;
double r=sqrt((double)(dx*dx+dy*dy)); aa.screenrad=r*zoom;
aa.relrad=r;
// We want to find the angle that's closes to ascreenprev
double aprev=ascreenprev-bias;
double ang=myatan2(dy,dx); ang=ang-bias;
if (ang<-100 || ang>100) ang=0; // !!!
while (ang>aprev+pi) ang-=2*pi; while (ang<aprev-pi) ang+=2*pi;
while (ang>2*pi) ang-=2*pi; while (ang<-2*pi) ang+=2*pi;
aa.relang=ang; aa.screenang=ang+bias;
aa.f=1; aa.isin = true;
return aa;
}
void TEditor::ShowHitTest()
{ RECT rc; GetClientRect(chwnd,&rc);
HDC hdc=GetDC(chwnd);
for (int y=rc.top; y<rc.bottom; y++)
{ for (int x=rc.left; x<rc.right; x++)
{ THitTest t = PointAtCoords(x,y,false);
if (t.type!=htMiss && t.s==hit.s)
{ COLORREF c;
if (t.type==htShape) c=RGB(255,0,0);
else if (t.type==htAroot) c=RGB(0,255,0);
else if (t.type==htSpot) c=RGB(0,0,255);
else {int i=t.si*31; i=i%255; c=RGB(i,i,i);}
SetPixel(hdc,x,y,c);
}
}
}
ReleaseDC(chwnd,hdc);
}
void TEditor::ObjectsInRect(double x0,double y0,double x1,double y1,list<int> &limbs,list<int> &shapes)
{ limbs.clear(); shapes.clear();
for (int sh=(int)body->shapes.size()-1; sh>=0; sh--)
{ stk::TShape &shape = body->shapes[sh];
bool simplecircle = (!shape.limbs && shape.p.size()==2 && shape.p[0].i==shape.p[1].i && shape.p[0].ar!=shape.p[1].ar && body->limbs[shape.p[0].i].type==3);
if (simplecircle)
{ TLimb &limb = body->limbs[shape.p[0].i];
double dx=limb.x-limb.x0,dy=limb.y-limb.y0, rad=sqrt(dx*dx+dy*dy);
if (limb.x0-rad>=x0 && limb.x0+rad<=x1 && limb.y0-rad>=y0 && limb.y0+rad<=y1)
{ shapes.push_back(sh);
int li = circlelimb_from_shape(sh); LUASSERT(li!=-1);
limbs.push_back(li);
}
}
if (!shape.limbs && shape.p.size()>0 && !simplecircle) // for a real shape...
{ // we'll only check its vertices
bool isin=true;
for (int si=0; si<(int)shape.p.size() && isin; si++)
{ TJointRef j0=shape.p[si];
double x,y; jointpos(&x,&y,body->limbs[j0.i],j0.ar);
if (x<x0 || x>x1 || y<y0 || y>y1) isin=false;
}
if (isin) shapes.push_back(sh);
}
//
if (shape.limbs)
{ for (int i=1; i<body->nlimbs; i++)
{ TLimb &limb=body->limbs[i];
bool isin=true, circle=false;
if (limb.type==0 || limb.type==2) // a line
{ if (limb.x<x0 || limb.x>x1 || limb.y<y0 || limb.y>y1) isin=false;
if (limb.x0<x0 || limb.x0>x1 || limb.y0<y0 || limb.y0>y1) isin=false;
}
else if (limb.type==1) // an arc
{ if (limb.x<x0 || limb.x>x1 || limb.y<y0 || limb.y>y1) isin=false;
double x,y; jointpos(&x,&y,limb,true);
if (x<x0 || x>x1 || y<y0 || y>y1) isin=false;
}
else if (limb.type==3) // a circle
{ double dx=limb.x-limb.x0,dy=limb.y-limb.y0, rad=sqrt(dx*dx+dy*dy);
if (limb.x0-rad<x0 || limb.x0+rad>x1 || limb.y0-rad<y0 || limb.y0+rad>y1) isin=false;
circle=true;
}
if (isin) limbs.push_back(i);
if (isin && circle) {int si=circleshape_from_limb(i); if (si!=-1) shapes.push_back(si);}
}
}
}
limbs.sort(); limbs.unique(); shapes.sort(); shapes.unique();
}
THitTest TEditor::PointAtCoords(int sx,int sy,bool isrightclick)
{ THitTest t; t.s=-1; t.sf=0; t.si=-1; t.n=-1; t.type=htMiss;
int limbs=-1; for (int i=0; i<(int)body->shapes.size() && limbs==-1; i++) {if (body->shapes[i].limbs) limbs=i;}
// Did we click on a rotation handle, or the pie, for the current selection?
for (list<int>::const_iterator sli=sellimbs.begin(); sli!=sellimbs.end(); sli++)
{ TLimb &sel=body->limbs[*sli];
bool showmin=(sel.chan!=4 || sel.band!=0), showmax=showmin;
if (sel.type==1) showmin=true;
if (sel.type==0 || sel.type==1)
{ int a1x=b2x(sel.x0)+(int)(((double)ArmLength)*cos(sel.ang1)), a1y=b2y(sel.y0)+(int)(((double)ArmLength)*sin(sel.ang1));
int a0x=b2x(sel.x0)+(int)(((double)ArmLength)*cos(sel.ang0)), a0y=b2y(sel.y0)+(int)(((double)ArmLength)*sin(sel.ang0));
if (showmax && sx>=a1x-ArmSpotLength && sx<a1x+ArmSpotLength && sy>=a1y-ArmSpotLength && sy<a1y+ArmSpotLength) {t.n=*sli; t.s=limbs; t.type=htAmax; return t;}
if (showmin && sx>=a0x-ArmSpotLength && sx<a0x+ArmSpotLength && sy>=a0y-ArmSpotLength && sy<a0y+ArmSpotLength) {t.n=*sli; t.s=limbs; t.type=htAmin; return t;}
if (isrightclick) // on a right click we're willing to check if it was a pie click
{ TAdjAngle a=AngleFromOff(x2b(sx)-sel.x0,y2b(sy)-sel.y0,sel.ang0,sel.aoff,sel.ang-sel.ang0);
if (a.isin && a.screenrad<SelPieLength) {t.n=*sli; t.s=limbs; t.type=htPie; return t;}
}
}
}
// Did we click on a spring handle for the current selection?
for (list<int>::const_iterator sli=sellimbs.begin(); sli!=sellimbs.end(); sli++)
{ TLimb &sel=body->limbs[*sli];
if (sel.type==2 || sel.type==3)
{ bool showmin=(sel.chan!=4 || sel.band!=0), showmax=showmin;
double ddx=cos(sel.ang+0.5*pi)*ArmLength/2, ddy=sin(sel.ang+0.5*pi)*ArmLength/2; int dx=(int)ddx, dy=(int)ddy;
int a0x=b2x(sel.x0+sel.lmin*cos(sel.ang))-dx, a0y=b2y(sel.y0+sel.lmin*sin(sel.ang))-dy;
int a1x=b2x(sel.x0+sel.length*cos(sel.ang))-dx, a1y=b2y(sel.y0+sel.length*sin(sel.ang))-dy;
if (showmax && sx>=a1x-ArmSpotLength && sx<a1x+ArmSpotLength && sy>=a1y-ArmSpotLength && sy<a1y+ArmSpotLength) {t.n=*sli; t.s=limbs; t.type=htAmax; return t;}
if (showmin && sx>=a0x-ArmSpotLength && sx<a0x+ArmSpotLength && sy>=a0y-ArmSpotLength && sy<a0y+ArmSpotLength) {t.n=*sli; t.s=limbs; t.type=htAmin; return t;}
}
}
// we check pins of the current shapes before anything else.
for (list<int>::const_iterator ssi=selshapes.begin(); ssi!=selshapes.end(); ssi++)
{ stk::TShape &shape = body->shapes[*ssi];
// if the thing is a circle/shape, then don't treat its pins as pins
int li=circlelimb_from_shape(*ssi);
if (li==-1)
{ for (int si=0; si<(int)shape.p.size(); si++)
{ TLimb &limb = body->limbs[shape.p[si].i]; bool ar=shape.p[si].ar;
double x,y; jointpos(&x,&y,limb,ar,0);
int cx=b2x(x), cy=b2y(y); double dx=sx-cx, dy=sy-cy, dd=dx*dx+dy*dy;
if (dd<SpotLength*SpotLength*2) {t.s=*ssi; t.si=si; t.sf=0; t.n=-1; t.type=htSpot; return t;}
}
}
}
// we must check all joints before checking any lines.
for (int i=0; i<body->nlimbs; i++)
{ TLimb &limb=body->limbs[i];
int cx=b2x(limb.x), cy=b2y(limb.y); double dx=sx-cx, dy=sy-cy, dd=dx*dx+dy*dy;
if (dd<SpotLength*SpotLength*2) {t.n=i; t.s=limbs; t.type=htSpot; return t;}
if (limb.type==1 || limb.type==3) // also check the endpoint of an arc/circle
{ double x,y; jointpos(&x,&y,limb,true,0);
cx=b2x(x); cy=b2y(y); dx=sx-cx; dy=sy-cy; dd=dx*dx+dy*dy;
if (dd<SpotLength*SpotLength*2) {t.n=i; t.s=limbs; t.type=htAroot; return t;}
}
}
// now check the lines and shapes...
// if there is a currently just-hit shape, its lines will have precedence over lines-as-limbs.
TEffPt ept;
int firsts=(int)body->shapes.size()-1; if (hit.s!=-1 && hit.n==-1) firsts++;
for (int shi=firsts; shi>=0; shi--)
{ int sh=shi; bool checkingsel = (shi==(int)body->shapes.size());
if (checkingsel) sh=hit.s;
stk::TShape &shape = body->shapes[sh];
bool simplecircle = (!shape.limbs && shape.p.size()==2 && shape.p[0].i==shape.p[1].i && shape.p[0].ar!=shape.p[1].ar && body->limbs[shape.p[0].i].type==3);
if (simplecircle)
{ TLimb &limb = body->limbs[shape.p[0].i];
double dx=limb.x-limb.x0,dy=limb.y-limb.y0, rad=sqrt(dx*dx+dy*dy);
double x0=b2x(limb.x0), y0=b2y(limb.y0), sr=b2x(limb.x0+rad)-x0;
double mr=sqrt((sx-x0)*(sx-x0) + (sy-y0)*(sy-y0));
double drad = sr-mr;
if (drad<4 && drad>-4) {t.n=-1; t.s=sh; t.sf=0; t.si=0; t.type=htLine; return t;}
if (!checkingsel && shape.brush.type!=ctNone && mr<sr) {t.n=-1; t.s=sh; t.sf=0; t.si=-1; t.type=htShape; return t;}
}
if (!shape.limbs && shape.p.size()>0 && !simplecircle) // for a real shape...
{ // first, we'll built the pt[] array for this shape
int ptpos=0; for (int si=0; si<(int)shape.p.size(); si++)
{ TJointRef j0=shape.p[si], j1=shape.p[(si+1)%shape.p.size()];
TLimb &limb0=body->limbs[j0.i]; //, &limb1=body->limbs[j1.i];
if (j0.i==j1.i && j0.ar!=j1.ar && (limb0.type==1 || limb0.type==3)) ptpos=add_arc(gb2x,gb2y,this,&ept,ptpos,limb0,j0.ar,si);
else ptpos=add_pt(gb2x,gb2y,this,&ept,ptpos,limb0,j0.ar,si);
}
if (shape.p.size()>2) ptpos=ept.add(ptpos,ept.pt[0].x,ept.pt[0].y,shape.p.size()-1); // to close it!
// Now we have the pt[] array. We check for line-clicks first.
RECT brc={0,0,0,0}; // we'll also figure out a bounding rectangle
for (int i=0; i<ptpos; i++)
{ double x0=ept.pt[i].x, y0=ept.pt[i].y;
double x1=ept.pt[(i+1)%ptpos].x, y1=ept.pt[(i+1)%ptpos].y;
double x=sx, y=sy;
x0+=0.0001; y0+=0.0001; // for divide-by-zero problems...
double m=(y1-y0)/(x1-x0), c=y1-m*x1; // equation of line joining points
double am=-1/m, ac=sy-am*x; // equation of perpendicular
double xd=(ac-c)/(m-am), yd=m*xd+c; // coordinates of closest point on line
double dx=xd-x, dy=yd-y, dd=dx*dx+dy*dy;
double dh=(x1-x0)*(x1-x0), dv=(y1-y0)*(y1-y0);
double f; if (dh>dv) f=(xd-x0)/(x1-x0); else f=(yd-y0)/(y1-y0);
double dmax; if (shi==(int)body->shapes.size()) dmax=26.0; else dmax=13.0; // big for current selection
if (dd<dmax && f>0 && f<1) {t.n=-1; t.s=sh; t.sf=f; t.si=ept.pi[i]; t.type=htLine; return t;}
int xx=ept.pt[i].x, yy=ept.pt[i].y;
if (i==0) {brc.left=xx; brc.top=yy; brc.right=xx; brc.bottom=yy;}
else {if (xx<brc.left) brc.left=xx; if (xx>brc.right) brc.right=xx; if (yy<brc.top) brc.top=yy; if (yy>brc.bottom) brc.bottom=yy;}
}
// now check to see if it's inside the polygon, but not on sh=-1 for the current shape
POINT ps; ps.x=sx; ps.y=sy;
if (!checkingsel && shape.brush.type!=ctNone && shape.p.size()>2 && inpoly(ept.pt,ptpos,ps,brc))
{ t.n=-1; t.s=sh; t.sf=0; t.si=-1; t.type=htShape; return t;
}
}
//
if (shape.limbs)
{ for (int i=1; i<body->nlimbs; i++)
{ TLimb &limb=body->limbs[i];
int dx=b2x(limb.x)-b2x(limb.x0), dy=b2y(limb.y)-b2y(limb.y0);
int dist=dx*dx+dy*dy;
bool islimblong = (dist>12);
if (islimblong && (limb.type==2 || limb.type==0)) // a line
{ double x0=0.01+(double)b2x(limb.x0), y0=0.01+(double)b2y(limb.y0), x1=b2x(limb.x), y1=b2y(limb.y);
double x=sx, y=sy;
double m=(y1-y0)/(x1-x0), c=y1-m*x1; // equation of line joining points
double am=-1/m, ac=sy-am*x; // equation of perpendicular
double xd=(ac-c)/(m-am), yd=m*xd+c; // coordinates of closest point on line
double dx=xd-(double)x, dy=yd-(double)y;
double dd=dx*dx+dy*dy;
double f=(xd-x0)/(x1-x0);
if (dd<13.0 && f>0 && f<1) {t.n=i; t.s=limbs; t.type=htLine; return t;}
}
else if (islimblong && limb.type==1) // an arc
{ double aoff=limb.aoff;
if (limb.chan==4 && limb.band==0) aoff=limb.ang-limb.ang0; // for a fixed-frequency arc
TAdjAngle a=AngleFromOff(x2b(sx)-limb.x0,y2b(sy)-limb.y0,limb.ang0,aoff,limb.ang-limb.ang0);
double drad=a.screenrad-zoom*limb.length;
if (drad<4 && drad>-4 && a.isin) {t.n=i; t.s=limbs; t.type=htLine;return t;}
}
else if (islimblong && limb.type==3) // a circle
{ TAdjAngle a=AngleFromOff(x2b(sx)-limb.x0,y2b(sy)-limb.y0,limb.ang0,limb.aoff,limb.ang-limb.ang0);
double dx=limb.x-limb.x0,dy=limb.y-limb.y0; double len=sqrt(dx*dx+dy*dy);
double drad=a.screenrad-zoom*len;
if (drad<4 && drad>-4) {t.n=i; t.s=limbs; t.type=htLine;return t;}
}
}
}
}
if (isrightclick && hit.n>0 && body->limbs[hit.n].type==2)
{ // for a right-click, we check if the user clicked on the spring itself.
// do this last, so the spring doesn't obscure the line or the point.
TLimb &sel=body->limbs[hit.n];
double ddx=cos(sel.ang+0.5*pi)*SelPieLength/2, ddy=sin(sel.ang+0.5*pi)*SelPieLength/2; int dx=(int)ddx, dy=(int)ddy;
POINT pt[4], p, s; s.x=sx; s.y=sy; int x,y;
x=b2x(sel.x0+sel.lmin*cos(sel.ang)); y=b2y(sel.y0+sel.lmin*sin(sel.ang));
pt[0].x=x+dx; pt[0].y=y+dy; pt[1].x=x-dx; pt[1].y=y-dy;
x=b2x(sel.x0+sel.length*cos(sel.ang)); y=b2y(sel.y0+sel.length*sin(sel.ang));
pt[2].x=x-dx; pt[2].y=y-dy; pt[3].x=x+dx; pt[3].y=y+dy;
p.x=(pt[0].x+pt[1].x+pt[2].x+pt[3].x)/4; p.y=(pt[0].y+pt[1].y+pt[2].y+pt[3].y)/4;
// the line (sx,sy)-(x,y) goes from the click to the center of the spring.
// if this intersects any of the lines, then the click must have been outside
bool isout = intersects(p,s, pt[0],pt[1]);
isout |= intersects(p,s, pt[1],pt[2]);
isout |= intersects(p,s, pt[2],pt[3]);
isout |= intersects(p,s, pt[3],pt[0]);
if (!isout) {t.n=hit.n; t.s=limbs; t.type=htPie; return t;}
}
return t;
}
void RecFlip(TBody *body, int n)
{ TLimb &limb = body->limbs[n];
//TLimb &root = body->limbs[limb.root];
//
if (limb.chan==4 && limb.band==0)
{ // a fixed limb. Ignores ang0,ascale, and uses just 'f'
if (limb.root!=0 && limb.aisoff)
{ limb.f = 2*pi-limb.f;
}
}
else
{ // Flip ang0. (we do this if the limb is relative to some root angle, but not if it's got a fixed base)
if (limb.root!=0 && limb.aisoff)
{ limb.aoff = 2*pi-limb.aoff;
}
// Flip ascale. (we do this for everything, even springs and fixeds.)
limb.ascale = -limb.ascale;
}
// now do the recursive bit
for (int i=0; i<body->nlimbs; i++)
{ if (body->limbs[i].root==n) RecFlip(body,i);
}
}
void TEditor::Flip()
{ if (sellimbs.size()==0) return;
list<int> toflip; GetRootLimbsOfSellimbs(&toflip);
MarkUndo();
ismodified=true;
for (list<int>::const_iterator i=toflip.begin(); i!=toflip.end(); i++)
{ RecFlip(body,*i); Recalc(*i);
}
Redraw(); SetCursor();
}
void TEditor::RecStretch(int n,double scale)
{ if (n!=0)
{ body->limbs[n].length *= scale;
body->limbs[n].lmin *= scale;
}
for (int i=1; i<body->nlimbs; i++)
{ if (body->limbs[i].root==n) RecStretch(i,scale);
}
}
void TEditor::Stretch(int dir)
{ if (dir==0) return;
MarkUndo();
bool tiny = (GetAsyncKeyState(VK_SHIFT)<0);
double scale=0;
if (dir>0 && tiny) scale=1.01;
else if (dir>0 && !tiny) scale=1.10;
else if (dir<0 && tiny) scale=0.99;
else if (dir<0 && !tiny) scale=0.9;
// now we find which ones to stretch. If nothing was selected,
// then we rec-stretch from the root 0. If stuff was, then we
// find the smallest set of root ancestors and stretch them.
list<int> tostretch; if (sellimbs.size()==0) tostretch.push_back(0);
else GetRootLimbsOfSellimbs(&tostretch);
for (list<int>::const_iterator i=tostretch.begin(); i!=tostretch.end(); i++)
{ RecStretch(*i,scale);
}
ismodified=true;
if (tostretch.size()==1) Recalc(tostretch.front()); else Recalc(0);
Redraw(); SetCursor();
}
void TEditor::DeleteLimbOrShape()
{ if (sellimbs.size()==0 && selshapes.size()==0) return;
MarkUndo();
int newsel=-1; // for if we want to select a new limb out of all this.
if (sellimbs.size()==1 && selshapes.size()==0)
{ int sel=sellimbs.front();
newsel=body->limbs[sel].root;
}
// first we'll delete all the selected shapes, then all the limbs.
// That way, even if deleting a limb would cause a shape to be deleted,
// the shape will already have been dealt with.
selshapes.sort(); int sub=0;
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ int li = *i;
int si = li-sub;
body->shapes.erase(body->shapes.begin()+si);
sub++;
}
sellimbs.sort(); sub=0;
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ int li = *i;
int si = li-sub;
if (si!=0) {body->DeleteLimb(si); sub++;}
}
hit.s=-1; hit.n=-1; selshapes.clear(); sellimbs.clear();
cori=-1; hit.type=htMiss; mode=mNothing;
if (newsel!=-1)
{ hit.n=newsel; sellimbs.push_back(newsel);
for (int i=0; i<(int)body->shapes.size(); i++) {if (body->shapes[i].limbs) hit.s=i;}
}
ismodified=true;
Recalc(0);
Redraw(); SetCursor();
UpdateMenus();
ShowHint("");
}
void TEditor::InsertLimb()
{ if (sellimbs.size()!=1) return;
int node=sellimbs.front();
MarkUndo();
TLimb n; TLimb &limb=body->limbs[node];
n.type=limb.type;
n.root=limb.root;
n.aisoff=limb.aisoff; n.chan=limb.chan; n.band=limb.band; n.anchor=limb.anchor;
n.aoff=limb.aoff; n.ascale=limb.ascale; n.f=limb.f;
n.length=limb.length/2; n.lmin=limb.lmin/2;
limb.length=limb.length/2; limb.lmin=limb.lmin/2;
n.x0=limb.x0; n.y0=limb.y0;
if (limb.color.type==ctNone) n.color.type=ctNone;
else { n.color.type = ctRGB; n.color.rgb.r = 255; n.color.rgb.g = 255; n.color.rgb.b = 255; }
n.color.dtype=n.color.type;
n.thickness=1;
int in=body->CreateLimb(n);
body->limbs[node].root=in;
body->MakeChildren();
Recalc(in);
//
mode=mNothing; hit.n=in; hit.type=htMiss; sellimbs.clear(); selshapes.clear(); sellimbs.push_back(hit.n);
ismodified=true;
Redraw(); SetCursor();
ShowHint("");
}
bool TEditor::Copy()
{ list<int> roots; GetRootLimbsOfSelection(&roots); if (roots.size()==0) return false;
int len=body->WriteData(NULL,0,roots); if (len==0) return false;
// now we have to figure out what extra stuff we'll need.
// First, we'll make a 'bitmap' of the limbs and shapes to be saved.
vector<bool> keep; keep.resize(body->nlimbs,false); bool changed=true;
for (list<int>::const_iterator i=roots.begin(); i!=roots.end(); i++) keep[*i]=true;
while (changed)
{ changed=false;
for (int n=0; n<body->nlimbs; n++)
{ int r=body->limbs[n].root;
if (keep[r] && !keep[n]) {keep[n]=true; changed=true;}
}
}
vector<bool> keepshapes; keepshapes.resize(body->shapes.size(),false);
for (int s=0; s<(int)body->shapes.size(); s++)
{ stk::TShape &shape = body->shapes[s]; bool ok=true;
if (shape.limbs) continue;
for (int i=0; i<(int)shape.p.size(); i++)
{ TJointRef pt = shape.p[i];
if (!keep[pt.i]) ok=false;
}
if (ok) keepshapes[s]=true;
}
// now we can make the list of bitmaps to keep
list<int> keepbitmaps;
for (int i=0; i<body->nlimbs; i++)
{ if (keep[i] && body->limbs[i].type==3)
{ int si=circleshape_from_limb(i);
if (si!=-1)
{ if (body->shapes[si].brush.type==ctBitmap) keepbitmaps.push_back(body->shapes[si].brush.bindex);
}
}
}
keepbitmaps.sort(); keepbitmaps.unique();
// now we'll figure out how to lay the bitmaps out in memory
unsigned int blen=0;
for (list<int>::const_iterator i=keepbitmaps.begin(); i!=keepbitmaps.end(); i++)
{ blen+=MAX_PATH; // name
blen+=sizeof(DWORD); // size
blen+=body->bmps[*i].bufsize;
}
// figure out which styles we need
list<string> keepstyles;
for (int i=0; i<body->nlimbs; i++)
{ if (keep[i])
{ if (body->limbs[i].linestyle!="") keepstyles.push_back(body->limbs[i].linestyle);
if (body->limbs[i].freqstyle!="") keepstyles.push_back(body->limbs[i].freqstyle);
}
}
for (int s=0; s<(int)body->shapes.size(); s++)
{ if (keepshapes[s])
{ if (body->shapes[s].linestyle!="") keepstyles.push_back(body->shapes[s].linestyle);
if (body->shapes[s].fillstyle!="") keepstyles.push_back(body->shapes[s].fillstyle);
}
}
keepstyles.sort(); keepstyles.unique();
// and again, layout in memory
unsigned int slen=StylesToString(NULL,0,body->styles);
//
// that's it! got all the data we need!
HGLOBAL hglob=GlobalAlloc(GMEM_DDESHARE|GMEM_MOVEABLE,3*sizeof(DWORD)+blen+slen+len);
char *c=(char*)GlobalLock(hglob);
*((DWORD*)c) = keepbitmaps.size(); c+=sizeof(DWORD);
*((DWORD*)c) = slen; c+=sizeof(DWORD);
*((DWORD*)c) = len; c+=sizeof(DWORD);
for (list<int>::const_iterator i=keepbitmaps.begin(); i!=keepbitmaps.end(); i++)
{ TBmp &bmp = body->bmps[*i];
strcpy(c,bmp.name.c_str()); c+=MAX_PATH;
*((DWORD*)c) = bmp.bufsize; c+=sizeof(DWORD);
memcpy(c,bmp.buf,bmp.bufsize); c+=bmp.bufsize;
}
StylesToString(c,slen,body->styles); c+=slen;
body->WriteData(c,len,roots); // unused c+=len;
GlobalUnlock(hglob);
OpenClipboard(mhwnd);
EmptyClipboard();
SetClipboardData(StickClipboardFormat,hglob);
CloseClipboard();
return true;
}
void TEditor::Cut()
{ list<int> roots;
GetRootLimbsOfSelection(&roots); // this is the same routine that Copy uses.
if (roots.size()==0) return;
Copy();
MarkUndo();
int root = roots.front(); root=body->limbs[root].root;
vector<int> remap; remap.resize(body->nlimbs);
for (list<int>::iterator i=roots.begin(); i!=roots.end(); i++)
{ body->DeleteBranch(*i,&remap);
list<int>::iterator j=i; j++; for (; j!=roots.end(); j++)
{ int oldlimb = *j; LUASSERT(oldlimb!=-1);
int newlimb = remap[oldlimb]; LUASSERT(newlimb!=-1);
*j = newlimb;
}
}
sellimbs.clear(); selshapes.clear();
hit.n=root; sellimbs.push_back(root); hit.type=htMiss; mode=mNothing;
ismodified=true;
if (roots.size()==1) Recalc(root); else Recalc(0);
Redraw(); SetCursor();
ShowHint("");
}
void TEditor::Paste()
{ if (sellimbs.size()>1) return;
if (!IsClipboardFormatAvailable(StickClipboardFormat)) return;
char err[1000];
OpenClipboard(mhwnd);
HANDLE hglob=GetClipboardData(StickClipboardFormat);
DWORD size=GlobalSize(hglob);
char *clip=(char*)GlobalLock(hglob);
char *buf=new char[size+1]; CopyMemory(buf,clip,size);
GlobalUnlock(hglob);
CloseClipboard();
char *c=buf;
int numbmps = *((DWORD*)c); c+=sizeof(DWORD);
unsigned int stylelen = *((DWORD*)c); c+=sizeof(DWORD);
unsigned int sticklen = *((DWORD*)c); c+=sizeof(DWORD); sticklen; // unused
// First we have to find if the new bitmaps will be any different from our existing ones
// That'll determine whether we have to MarkUndo with bitmaps or can make do without
list<TBmp> newbmps;
for (int i=0; i<numbmps; i++)
{ TBmp b; b.name=string(c); c+=MAX_PATH;
b.bufsize = *((DWORD*)c); c+=sizeof(DWORD);
b.buf = c; c+=b.bufsize;
bool alreadyin=false;
for (vector<TBmp>::const_iterator bi=body->bmps.begin(); bi!=body->bmps.end() && !alreadyin; bi++)
{ if (StringLower(bi->name)==StringLower(b.name)) alreadyin=true;
}
if (!alreadyin) newbmps.push_back(b);
}
//
MarkUndo(newbmps.size()>0);
// read in the bitmap data
for (list<TBmp>::const_iterator i=newbmps.begin(); i!=newbmps.end(); i++)
{ TBmp b; b.name=i->name; b.bufsize=i->bufsize; b.buf=new char[b.bufsize]; memcpy(b.buf,i->buf,b.bufsize);
PrepareBitmapData(&b,true);
body->bmps.push_back(b);
}
// read in the style data
list<TStyle> newstyles;
StylesFromString(c,newstyles); c+=stylelen;
// read in the stick data
list<int> roots; bool res=body->ReadData(c,err,rdMerge,&roots);
if (!res) {delete[] buf; MessageBox(mhwnd,err,"Unable to paste",MB_OK); return;}
// delete the buffer
delete[] buf;
//
// now for the fixups...
// first, for the styles
for (list<TStyle>::const_iterator i=newstyles.begin(); i!=newstyles.end(); i++)
{ string name=i->name; bool alreadypresent=false;
for (list<TStyle>::const_iterator j=body->styles.begin(); j!=body->styles.end() && !alreadypresent; j++)
{ if (name==j->name) alreadypresent=true;
}
if (!alreadypresent) body->styles.push_back(*i);
else ApplyStyle(name,true);
}
// second, for the limb structure
int pastepoint=hit.n;
if (pastepoint<0) pastepoint=0;
for (list<int>::const_iterator i=roots.begin(); i!=roots.end(); i++)
{ body->limbs[*i].root=pastepoint;
body->limbs[*i].f=0.001*(double)(rand()%1000);
}
body->MakeChildren();
// bitmaps
MakeBindexes(body); MakeEindexes(body);
//
ismodified=true;
Recalc(pastepoint);
Redraw(); SetCursor();
ShowHint("");
}
void TEditor::Backdrop(const string afn,bool suppressredraw)
{ string s=afn;
if (s=="?")
{ char fn[MAX_PATH];
OPENFILENAME ofn; ZeroMemory(&ofn,sizeof(ofn)); ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=mhwnd;
ofn.lpstrFilter="Bitmaps\0*.bmp\0\0";
ofn.nFilterIndex=0;
ofn.lpstrFile=fn; strcpy(fn,"");
ofn.nMaxFile=MAX_PATH;
ofn.lpstrFileTitle=NULL;
string root = GetStickDir();
ofn.lpstrInitialDir=root.c_str();
ofn.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
ofn.lpstrDefExt="bmp";
BOOL res=GetOpenFileName(&ofn);
if (!res) return;
s=ofn.lpstrFile;
}
if (hbackdrop!=0) {DeleteObject(hbackdrop); hbackdrop=0; fnbackdrop=""; ismodified=true;}
if (afn=="") {if (!suppressredraw) {Redraw(); UpdateMenus();} return;}
hbackdrop = (HBITMAP)LoadImage(NULL,s.c_str(),IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
if (hbackdrop!=0) fnbackdrop=s;
ismodified=true; if (!suppressredraw) {Redraw(); UpdateMenus();}
}
void TEditor::Recalc(int n)
{ if (n==0) body->Recalc();
else body->RecalcLimb(n);
body->RecalcEffects(true);
}
void SaveBack(const string ffn,const string back)
{ string fn=StringLower(ExtractFileName(ffn));
for (list<TUserBack>::iterator i=UserBacks.begin(); i!=UserBacks.end(); i++)
{ if (i->fn==fn) {i->back=back; return;}
}
if (UserBacks.size()>10) UserBacks.pop_back();
TUserBack ub; ub.fn=fn; ub.back=back; UserBacks.push_front(ub);
}
string RecallBack(const string ffn)
{ string fn=StringLower(ExtractFileName(ffn));
for (list<TUserBack>::iterator i=UserBacks.begin(); i!=UserBacks.end(); i++)
{ if (i->fn==fn)
{ TUserBack ub=*i;
UserBacks.erase(i); UserBacks.push_front(ub); // give it higher priority
return ub.back;
}
}
return "";
}
bool SaveBody(TBody *body,const char *fn)
{ HANDLE hFile=CreateFile(fn,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (hFile==INVALID_HANDLE_VALUE) return false;
// We will first put in just a minimal almost dummy header, so that old
// versions don't choke. But the real data will follow, zipped up
string s = string("")+"nlimbs=0\r\nnshapes=1\r\nroot=0\r\n"
"version=" STK_CORE_S "\r\n"
"category="+body->category+"\r\n"
"limb(0)= line invisible root(0) angabs(0,3)(0) lmin(0) length(0) freq(4,0) frac(0) col(0,0,0) thickness(0)\r\n";
"shape(0)= limbs\r\n";
"\0";
DWORD writ; WriteFile(hFile,s.c_str(),s.length()+1,&writ,NULL);
// Now comes the zipped up data
HZIP hz = CreateZipHandle(hFile,NULL);
// first the stick figure itself
unsigned int len=body->WriteData(NULL,0,0); char *buf=new char[len];
body->WriteData(buf,len,0); while (len>0 && buf[len-1]==0) len--;
ZipAdd(hz,"mainstick.txt", buf,len);
delete[] buf;
// Now come the bitmaps
for (vector<TBmp>::const_iterator i=body->bmps.begin(); i!=body->bmps.end(); i++)
{ bool isbmp = (i->buf[0]=='B' && i->buf[1]=='M');
string ext; if (isbmp) ext=".bmp"; else ext=".jpg";
ZipAdd(hz,(i->name+ext).c_str(), i->buf,i->bufsize);
i->bufsize;
}
// Now come the styles
len = StylesToString(NULL,0,body->styles);
buf = new char[len]; StylesToString(buf,len,body->styles); while (len>0 && buf[len-1]==0) len--;
ZipAdd(hz,"styles.txt", buf,len);
delete[] buf;
// wasn't that zip easy?!
CloseZip(hz);
CloseHandle(hFile);
return true;
}
string TEditor::CleanBitmapName(const string s)
{ string broot=s;
for (int i=0; i<(int)broot.size(); i++)
{ if (broot[i]==')') broot[i]=']';
if (broot[i]=='(') broot[i]='[';
}
for (int i=1; ; i++)
{ string bname;
if (i==1) bname=broot; else bname=broot+StringInt(i);
bool okay=true;
for (vector<TBmp>::const_iterator ci=body->bmps.begin(); ci!=body->bmps.end() && okay; ci++)
{ if (StringLower(ci->name)==StringLower(bname)) okay=false;
}
if (okay) return bname;
}
}
string TEditor::AddBitmap(const char *fn)
{ bool isbmp=false, isjpeg=false;
HBITMAP hbm=(HBITMAP)LoadImage(hInstance,fn,IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION);
if (hbm!=0) {DeleteObject(hbm); isbmp=true;}
if (!isbmp)
{ HANDLE hf = CreateFile(fn,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
if (hf!=INVALID_HANDLE_VALUE)
{ DWORD size = GetFileSize(hf,NULL);
HGLOBAL hglob = GlobalAlloc(GMEM_MOVEABLE,size);
void *buf = GlobalLock(hglob);
DWORD red; ReadFile(hf,buf,size,&red,NULL);
GlobalUnlock(hglob);
CloseHandle(hf);
hbm = MakeJpeg(hglob,true);
GlobalFree(hglob);
if (hbm!=0) {DeleteObject(hbm); isjpeg=true;}
}
}
if (!isbmp && !isjpeg) return "";
//
TBmp bmp;
// pick a unique internal name for it
bmp.name = CleanBitmapName(stk::ChangeFileExt(stk::ExtractFileName(fn),""));
if (isjpeg) bmp.name+="-NT";
// load the raw data
HANDLE hf = CreateFile(fn,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
bmp.bufsize=GetFileSize(hf,NULL); bmp.buf = new char[bmp.bufsize];
DWORD red; ReadFile(hf,bmp.buf,bmp.bufsize,&red,NULL);
CloseHandle(hf);
PrepareBitmapData(&bmp,true);
// and add it into the list of things
body->bmps.push_back(bmp);
//
return bmp.name;
}
void TEditor::DeleteBitmap(const string zname)
{ MarkUndo(true);
for (vector<TBmp>::iterator ci=body->bmps.begin(); ci!=body->bmps.end(); ci++)
{ if (StringLower(ci->name)==StringLower(zname))
{ ci->release();
body->bmps.erase(ci);
// now remove any references to it
for (vector<stk::TShape>::iterator i=body->shapes.begin(); i!=body->shapes.end(); i++)
{ stk::TShape &shape = *i;
if (StringLower(shape.brush.bitmap)==StringLower(zname))
{ shape.brush.bitmap=""; shape.brush.bindex=-1;
if (shape.brush.type==ctBitmap) {shape.brush.type=ctNone; shape.brush.dtype=ctNone;}
}
}
for (vector<TEffect>::iterator i=body->effects.begin(); i!=body->effects.end(); i++)
{ TEffect &effect = *i;
for (vector<stk::TColor>::iterator j=effect.cols.begin(); j!=effect.cols.end(); j++)
{ if (StringLower(j->bitmap)==StringLower(zname))
{ j->bitmap=""; j->bindex=-1;
if (j->type == ctBitmap) { j->type = ctRGB; j->rgb.r = 128; j->rgb.g = 128; j->rgb.b = 128; }
}
}
}
for (list<TStyle>::iterator i=body->styles.begin(); i!=body->styles.end(); i++)
{ TStyle &style = *i;
if (StringLower(style.shape.brush.bitmap)==StringLower(zname))
{ style.shape.brush.bitmap=""; style.shape.brush.bindex=-1;
if (style.shape.brush.type==ctBitmap) {style.shape.brush.type=ctNone; style.shape.brush.dtype=ctNone;}
}
}
//
MakeBindexes(body); body->RecalcEffects(true);
ismodified=true;
Redraw();
return;
}
}
}
string TEditor::RenameBitmap(const string oldzn,const string newzn)
{ if (oldzn==newzn) return oldzn;
MarkUndo(true);
// ensure that the new name is unique
string realnew = CleanBitmapName(newzn);
// and rename it!
for (vector<TBmp>::iterator ci=body->bmps.begin(); ci!=body->bmps.end(); ci++)
{ if (StringLower(ci->name)==StringLower(oldzn))
{ ci->name=realnew;
PrepareBitmapData(&*ci,true);
//
for (vector<stk::TShape>::iterator i=body->shapes.begin(); i!=body->shapes.end(); i++)
{ stk::TShape &shape = *i;
if (StringLower(shape.brush.bitmap)==StringLower(oldzn)) shape.brush.bitmap=realnew;
}
for (vector<TEffect>::iterator i=body->effects.begin(); i!=body->effects.end(); i++)
{ TEffect &effect = *i;
for (vector<stk::TColor>::iterator j=effect.cols.begin(); j!=effect.cols.end(); j++)
{ if (StringLower(j->bitmap)==StringLower(oldzn)) j->bitmap=realnew;
}
}
for (list<TStyle>::iterator i=body->styles.begin(); i!=body->styles.end(); i++)
{ TStyle &style = *i;
if (StringLower(style.shape.brush.bitmap)==StringLower(oldzn)) style.shape.brush.bitmap=realnew;
}
//
MakeBindexes(body);
ismodified=true;
return realnew;
}
}
return oldzn;
}
bool TEditor::FileSave()
{ if (strcmp(curfile,"")==0) return FileSaveAs("");
bool res = MaybeCheckUpright();
if (!res) return false;
string tit = "Save "+stk::ExtractFileName(curfile);
DWORD attr = GetFileAttributes(curfile);
if (attr!=0xFFFFFFFF && (attr&FILE_ATTRIBUTE_READONLY)!=0)
{ int id=MessageBox(mhwnd,"The file is read-only. Are you sure you wish to replace it?",tit.c_str(),MB_ICONQUESTION|MB_YESNOCANCEL);
if (id!=IDYES) return false;
SetFileAttributes(curfile,attr&~FILE_ATTRIBUTE_READONLY);
}
res = SaveBody(body,curfile);
if (!res)
{ string msg = "There was an error saving the file:\r\n"+GetLastErrorString();
MessageBox(mhwnd,msg.c_str(),tit.c_str(),MB_ICONERROR|MB_OK);
return false;
}
SaveBack(curfile,fnbackdrop);
ismodified=false; ShowTitle();
string msg="Saved file "+stk::ChangeFileExt(stk::ExtractFileName(curfile),""); ShowHint(msg);
return true;
}
bool TEditor::FileSaveAs(char *afn)
{ bool mres = MaybeCheckUpright();
if (!mres) return false;
char fn[MAX_PATH];
OPENFILENAME ofn; ZeroMemory(&ofn,sizeof(ofn)); ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=mhwnd;
ofn.lpstrFilter="Sticks\0*.stk\0\0";
ofn.nFilterIndex=0;
string root = GetStickDir(); ofn.lpstrInitialDir=root.c_str();
ofn.lpstrFile=fn;
char *startswithroot=strstr(afn,root.c_str());
if (startswithroot!=NULL) strcpy(fn,afn+root.length()+1); else strcpy(fn,afn);
ofn.nMaxFile=MAX_PATH;
ofn.lpstrFileTitle=NULL;
ofn.Flags=OFN_OVERWRITEPROMPT|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
ofn.lpstrDefExt="stk";
BOOL res=GetSaveFileName(&ofn);
if (!res) return false;
//
string tit = "Save "+stk::ExtractFileName(fn);
DWORD attr = GetFileAttributes(fn);
if (attr!=0xFFFFFFFF && (attr&FILE_ATTRIBUTE_READONLY)!=0)
{ int id=MessageBox(mhwnd,"The file is read-only. Are you sure you wish to replace it?",tit.c_str(),MB_ICONQUESTION|MB_YESNOCANCEL);
if (id!=IDYES) return false;
SetFileAttributes(fn,attr&~FILE_ATTRIBUTE_READONLY);
}
res = SaveBody(body,fn);
if (!res)
{ string msg = "There was an error saving the file:\r\n"+GetLastErrorString();
MessageBox(mhwnd,msg.c_str(),tit.c_str(),MB_ICONERROR|MB_OK);
return false;
}
//
SaveBack(curfile,fnbackdrop);
strcpy(curfile,fn); ismodified=false; ShowTitle();
string msg="Saved file "+stk::ChangeFileExt(stk::ExtractFileName(fn),""); ShowHint(msg);
return true;
}
LRESULT CALLBACK ProcessionSubclassProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ HWND hpar = GetParent(hwnd); if (hpar==0) return DefWindowProc(hwnd,msg,wParam,lParam);
LONG_PTR oldproc = GetWindowLongPtr(hpar,GWLP_USERDATA); if (oldproc==0) return DefWindowProc(hwnd,msg,wParam,lParam);
switch (msg)
{ case WM_RBUTTONDOWN:
{ if (exportpre.size()==0)
{ SetCapture(hwnd); SetCursor(LoadCursor(NULL,IDC_WAIT));
DirScan(exportpre,GetStickDir()+"\\",true);
SetCursor(LoadCursor(NULL,IDC_ARROW)); ReleaseCapture();
}
HMENU hmenu=CreatePopupMenu();
for (int i=(int)exportpre.size()-1; i>=0; i--)
{ string s = exportpre[i].desc;
PopulateMenu(hmenu,s.c_str(),1000+i,false);
}
POINT pt; pt.x=LOWORD(lParam); pt.y=HIWORD(lParam); ClientToScreen(hwnd,&pt);
int cmd=TrackPopupMenu(hmenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,hwnd,NULL);
DestroyMenu(hmenu);
if (cmd>=1000)
{ string stick = exportpre[cmd-1000].desc;
char s[5000]; GetWindowText(hwnd,s,5000); s[4999]=0; int len=strlen(s);
bool needcr=false;
if (len==0) {} // doesn't need it
else if (len==1) needcr=true;
else if (s[len-1]!='\n' || s[len-2]!='\r') needcr=true;
if (needcr) stick="\r\n"+stick;
strcat(s,stick.c_str()); SetWindowText(hwnd,s);
int id=GetWindowLongPtr(hwnd,GWLP_ID);
SendMessage(hpar,WM_COMMAND,(WPARAM)(id|(EN_CHANGE<<16)),(LPARAM)hwnd);
}
return 0;
}
}
return CallWindowProc((WNDPROC)oldproc,hwnd,msg,wParam,lParam);
}
string ListToString(const list<string> l)
{ string ss;
for (list<string>::const_iterator i=l.begin(); i!=l.end(); i++)
{ if (ss.length()!=0) ss=ss+"\r\n";
ss=ss+*i;
}
return ss;
}
list<string> StringToList(const string ss)
{ list<string> l;
const char *c=ss.c_str();
while (*c!=0)
{ const char *start=c; while (*c!='\r' && *c!='\n' && *c!=0) c++;
string s = StringTrim(string(start,c-start));
if (s.length()>0) l.push_back(s);
while (*c=='\r' || *c=='\n') c++;
}
return l;
}
int WINAPI ExportDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ TEditor *ed = (TEditor*)GetWindowLong(hdlg,DWL_USER);
switch (msg)
{ case WM_INITDIALOG:
{ ed = (TEditor*)lParam; SetWindowLong(hdlg,DWL_USER,(LONG)ed);
RECT rc; GetWindowRect(hdlg,&rc); int w=rc.right-rc.left, h=rc.bottom-rc.top;
RECT prc; GetWindowRect(GetParent(hdlg),&prc); int cx=(prc.left+prc.right)/2, cy=(prc.top+prc.bottom)/2;
if (cx-w/2<0) cx=w/2; if (cy-h/2<0) cy=h/2;
MoveWindow(hdlg,cx-w/2,cy-h/2,w,h,FALSE);
// subclass the edit box
HWND hed = GetDlgItem(hdlg,IDC_PROCESSIONLIST);
LONG_PTR oldproc = GetWindowLongPtr(hed,GWLP_WNDPROC);
SetWindowLongPtr(hdlg,GWLP_USERDATA,oldproc);
SetWindowLongPtr(hed,GWLP_WNDPROC,(LONG_PTR)ProcessionSubclassProc);
//
SetDlgItemText(hdlg,IDC_TIME,StringInt(exporttime/1000).c_str());
SetDlgItemText(hdlg,IDC_PROCTIME,StringNiceFloat(((double)exportproctime)/1000.0).c_str());
SetDlgItemText(hdlg,IDC_WAVNAME,exportwav.c_str());
CheckDlgButton(hdlg,IDC_SILENTDANCING, exporttune==0?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_SILENTTHRASHING, exporttune==1?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_DANCETOWAV, exporttune==2?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_TIMEFIXED,exporttimefixed?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_TIMEWAV,exporttimefixed?BST_UNCHECKED:BST_CHECKED);
SetDlgItemText(hdlg,IDC_WIDTH,StringInt(exportw).c_str());
SetDlgItemText(hdlg,IDC_HEIGHT,StringInt(exporth).c_str());
SetDlgItemText(hdlg,IDC_FPS,StringInt(exportfps).c_str());
if (exportcompress) CheckDlgButton(hdlg,IDC_SHOWCOMPRESSION,BST_CHECKED);
SetDlgItemText(hdlg,IDC_PROCESSIONLIST,exportfigs.c_str());
CheckDlgButton(hdlg,IDC_STICK_PROCESSION,exportproc?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_STICK_CURRENT,exportproc?BST_UNCHECKED:BST_CHECKED);
return TRUE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (id==IDCANCEL) EndDialog(hdlg,id);
if (id==IDC_TIME && code==EN_CHANGE)
{ CheckDlgButton(hdlg,IDC_TIMEWAV,BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_TIMEFIXED,BST_CHECKED);
}
if ((id==IDC_PROCTIME||id==IDC_PROCESSIONLIST) && code==EN_CHANGE)
{ CheckDlgButton(hdlg,IDC_STICK_CURRENT,BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_STICK_PROCESSION,BST_CHECKED);
}
if (id==IDC_WAVNAME && code==EN_CHANGE)
{ CheckDlgButton(hdlg,IDC_DANCETOWAV,BST_CHECKED);
CheckDlgButton(hdlg,IDC_SILENTDANCING,BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_SILENTTHRASHING,BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_TIMEWAV,BST_CHECKED);
CheckDlgButton(hdlg,IDC_TIMEFIXED,BST_UNCHECKED);
}
if (id==IDC_SILENTDANCING || id==IDC_SILENTTHRASHING)
{ if (IsDlgButtonChecked(hdlg,IDC_SILENTDANCING)==BST_CHECKED || IsDlgButtonChecked(hdlg,IDC_SILENTTHRASHING)==BST_CHECKED)
{ CheckDlgButton(hdlg,IDC_TIMEWAV,BST_UNCHECKED);
CheckDlgButton(hdlg,IDC_TIMEFIXED,BST_CHECKED);
}
}
if (id==IDC_WAVBROWSE && code==BN_CLICKED)
{ char fn[MAX_PATH];
OPENFILENAME ofn; ZeroMemory(&ofn,sizeof(ofn)); ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=hdlg;
ofn.lpstrFilter="WAV files\0*.wav\0\0";
ofn.nFilterIndex=0;
ofn.lpstrInitialDir=0;
ofn.lpstrFile=fn; GetDlgItemText(hdlg,IDC_WAVNAME,fn,MAX_PATH);
ofn.nMaxFile=MAX_PATH;
ofn.lpstrFileTitle=NULL;
ofn.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
ofn.lpstrDefExt="wav";
BOOL res=GetOpenFileName(&ofn);
if (res) SetDlgItemText(hdlg,IDC_WAVNAME,fn); // will also select this radio button
}
if (id==IDOK)
{ int nwidth,nheight,ntime,nfps,ntune,nproctime; string nwavname, nfigs;
char c[5000]; GetDlgItemText(hdlg,IDC_WIDTH,c,MAX_PATH); int res=sscanf(c,"%i",&nwidth);
if (res!=1 || nwidth<1 || nwidth>5000) {SetFocus(GetDlgItem(hdlg,IDC_WIDTH)); MessageBeep(0); return TRUE;}
GetDlgItemText(hdlg,IDC_HEIGHT,c,MAX_PATH); res=sscanf(c,"%i",&nheight);
if (res!=1 || nheight<1 || nheight>5000) {SetFocus(GetDlgItem(hdlg,IDC_HEIGHT)); MessageBeep(0); return TRUE;}
GetDlgItemText(hdlg,IDC_WAVNAME,c,MAX_PATH); nwavname=c;
if (GetFileAttributes(c)==0xFFFFFFFF)
{ if (IsDlgButtonChecked(hdlg,IDC_DANCETOWAV)==BST_CHECKED) {SetFocus(GetDlgItem(hdlg,IDC_WAVNAME)); MessageBeep(0); return TRUE;}
nwavname=exportwav;
}
if (IsDlgButtonChecked(hdlg,IDC_TIMEWAV)==BST_CHECKED && IsDlgButtonChecked(hdlg,IDC_DANCETOWAV)!=BST_CHECKED)
{ SetFocus(GetDlgItem(hdlg,IDC_TIMEWAV)); MessageBeep(0); return TRUE;
}
GetDlgItemText(hdlg,IDC_TIME,c,MAX_PATH); res=sscanf(c,"%i",&ntime);
if (res!=1 || ntime<1 || ntime>5000)
{ if (IsDlgButtonChecked(hdlg,IDC_TIMEFIXED)==BST_CHECKED) {SetFocus(GetDlgItem(hdlg,IDC_TIME)); MessageBeep(0); return TRUE;}
ntime=exporttime;
}
GetDlgItemText(hdlg,IDC_PROCTIME,c,MAX_PATH); double d; res=sscanf(c,"%lf",&d); nproctime=(int)(d*1000.0);
if (res!=1 || nproctime<1 || nproctime>50000)
{ if (IsDlgButtonChecked(hdlg,IDC_STICK_PROCESSION)==BST_CHECKED) {SetFocus(GetDlgItem(hdlg,IDC_PROCTIME)); MessageBeep(0); return TRUE;}
nproctime=exportproctime;
}
GetDlgItemText(hdlg,IDC_FPS,c,MAX_PATH); res=sscanf(c,"%i",&nfps);
if (res!=1 || nfps<1 || nfps>1000) {SetFocus(GetDlgItem(hdlg,IDC_FPS)); MessageBeep(0); return TRUE;}
// now we'll check that the procession list is okay
if (exportpre.size()==0)
{ SetCapture(hdlg); SetCursor(LoadCursor(NULL,IDC_WAIT));
DirScan(exportpre,GetStickDir()+"\\",true);
SetCursor(LoadCursor(NULL,IDC_ARROW)); ReleaseCapture();
}
GetDlgItemText(hdlg,IDC_PROCESSIONLIST,c,5000); c[4999]=0;
list<string> tfigs=StringToList(c);
bool sticksok=true;
for (list<string>::const_iterator i=tfigs.begin(); i!=tfigs.end(); i++)
{ string s=reggarble(*i); // turn it into a regexp
REGEXP re; regbegin(&re,s.c_str(),REG_ICASE);
bool stickok=false;
for (vector<TPre>::const_iterator i=exportpre.begin(); i!=exportpre.end(); i++)
{ bool res = regmatch(&re,i->desc.c_str(),NULL,0);
if (res) {stickok=true; break;}
}
regend(&re);
if (!stickok) sticksok=false;
}
nfigs=ListToString(tfigs);
if (!sticksok)
{ if (IsDlgButtonChecked(hdlg,IDC_STICK_PROCESSION)) {SetFocus(GetDlgItem(hdlg,IDC_PROCESSIONLIST)); MessageBeep(0); return TRUE;}
nfigs=exportfigs;
}
ntune=-1;
if (IsDlgButtonChecked(hdlg,IDC_SILENTDANCING)==BST_CHECKED) ntune=0;
if (IsDlgButtonChecked(hdlg,IDC_SILENTTHRASHING)==BST_CHECKED) ntune=1;
if (IsDlgButtonChecked(hdlg,IDC_DANCETOWAV)==BST_CHECKED) ntune=2;
if (ntune==-1) {SetFocus(GetDlgItem(hdlg,IDC_SILENTDANCING)); MessageBeep(0); return TRUE;}
//
// at this point, we're all okay.
exportw=nwidth;
exporth=nheight;
exporttime=ntime*1000;
exportproctime=nproctime;
exportfps=nfps;
exportwav=nwavname;
exportfigs=nfigs;
exporttune=ntune;
exportproc = (IsDlgButtonChecked(hdlg,IDC_STICK_PROCESSION)==BST_CHECKED);
exporttimefixed = (IsDlgButtonChecked(hdlg,IDC_TIMEFIXED)==BST_CHECKED);
exportcompress = (IsDlgButtonChecked(hdlg,IDC_SHOWCOMPRESSION)==BST_CHECKED);
EndDialog(hdlg,IDOK);
}
return TRUE;
}
}
return FALSE;
}
class TComplex
{ public:
TComplex () {}
TComplex (double re): _re(re), _im(0.0) {}
TComplex (double re, double im): _re(re), _im(im) {}
double Re () const { return _re; }
double Im () const { return _im; }
void operator += (const TComplex& c) {_re += c._re; _im += c._im;}
void operator -= (const TComplex& c) {_re -= c._re; _im -= c._im;}
void operator *= (const TComplex& c) { double reT = c._re * _re - c._im * _im;_im = c._re * _im + c._im * _re; _re = reT;}
TComplex operator- () { return TComplex (- _re, _im);}
double Mod () const { return sqrt (_re * _re + _im * _im); }
double _re;
double _im;
};
// Given a wav-file, renders it into 'sampledat' format, one sample every 41ms.
// Return value is the number of samples needed for the wavfile.
// If the array given is not large enough, or if sampledat is NULL,
// then no samples are actually written.
int TEditor::fft(WavChunk *wav, TSpot *spots, int spotsize)
{
// First, get basic information about the wav file.
int bitsps = wav->fmt.wBitsPerSample;
int nchan = wav->fmt.wChannels;
unsigned long totbytes = wav->dat.size;
unsigned long totsamples = (unsigned long)(((double)totbytes)*8.0/bitsps/nchan);
unsigned long totms = (unsigned long)(((double)totsamples)*1000.0/wav->fmt.dwSamplesPerSec);
int totspots = (int)(totms/41);
if (totsamples<1024) return 0; // can't do anything with a file this small!
if (totspots>spotsize) return totspots;
if (spots==0) return totspots;
//
// Prepare some constants and tables and pre-computed tables
const int npoints=1024; // must be a power of two
const double sqrtnpoints=32; // =sqrt(npoints)
const int logpoints=10; // binary log (ie. 2^10=1024)
//const int npoints=256;
//const double sqrtnpoints=16;
//const int logpoints=8;
//
int bitrev[npoints]; // precomputed bit-reversal table
TComplex W[logpoints+1][npoints]; // precomputed complex exponentials
// Precomputed complex exponentials:
for (int lg=1, twos=2; lg<=logpoints; lg++, twos*=2)
{ for (int i=0; i<npoints; i++ ) W[lg][i] = TComplex(cos(2.*pi*i/twos),-sin(2.*pi*i/twos));
}
// ... and bit reverse mapping
for (int rev=0, i=0; i<npoints-1; i++)
{ bitrev[i] = rev;
int mask = npoints/2;
while (rev >= mask) {rev-=mask; mask >>= 1;}
rev += mask;
}
bitrev[npoints-1] = npoints-1;
// Now go through the file building FFT data!
// On the first pass, we will store raw values in spots.l[], spots.r[]
// Also, we will use two arrays to store our FFT analysis of each spot:
double tape[2][npoints]; // the raw waveform (ie. time-domain) normalised into doubles
TComplex X[2][npoints]; // the frequency-domain
//
for (int spot=0; spot<totspots && !ExportCancelled; spot++)
{ string msg = "Finding the groove: "+StringInt(spot*100/totspots)+"%";
ShowHint(msg); PumpMessages();
//
unsigned long mspos = spot*41;
unsigned long samplepos = mspos*wav->fmt.dwSamplesPerSec/1000;
unsigned long startsample=0; if (samplepos>=npoints/2) startsample=samplepos-npoints/2;
if (startsample+npoints>totsamples) startsample=totsamples-npoints;
unsigned long startbyte = startsample*nchan*bitsps/8;
//
// copy the raw data into our tape, normalising it into doubles
unsigned char *bdat = (unsigned char*)wav->dat.data+startbyte;
signed short *wdat = (signed short*)bdat;
for (int i=0; i<npoints; i++)
{ if (bitsps==8)
{ tape[0][i] = (bdat[nchan*i+0]-128)*64;
if (nchan==1) tape[1][i]=tape[0][i];
else tape[1][i] = (bdat[nchan*i+1]-128)*64;
}
else
{ tape[0][i] = wdat[nchan*i+0];
if (nchan==1) tape[1][i]=tape[0][i];
else tape[1][i] = wdat[nchan*i+1];
}
}
// initialize the FFT buffer
for (int chan=0; chan<2; chan++)
{ for (int i=0; i<npoints; i++) X[chan][bitrev[i]]=TComplex(tape[chan][i]);
}
// do the transform
for (int chan=0; chan<2; chan++)
{ int step = 1;
for (int level=1; level<=logpoints; level++)
{ int increm = step*2;
for (int j=0; j<step; j++)
{ TComplex U = W[level][j]; // U=exp(-2PIj / 2^level)
for (int i=j; i<npoints; i+=increm)
{ TComplex T = U;
T *= X [chan][i+step];
X [chan][i+step] = X[chan][i];
X [chan][i+step] -= T;
X [chan][i] += T;
}
}
step *= 2;
}
}
// store in buckets, spots.l[] and spots.r[]
// 0: 450 - 772
// 1: 794 - 1117
// 2: 1134 - 1461
// 3: 1480 - 1827
// 4: 1827 - 2171
// 5: 2171 - 2515
double fftfreq = ((double)wav->fmt.dwSamplesPerSec)/2; // the maximum frequency of the fft
double maxfreq = fftfreq; if (maxfreq>2515) maxfreq=2515; // the max frequency we'll inspect
double minfreq = 450;
int boff = (int)(((double)npoints)*minfreq/fftfreq); // index of minfreq in X[] array
int bmax = (int)(((double)npoints)*maxfreq/fftfreq); // index of maxfreq
int bwidth = (bmax-boff)/6; // number of X[]s for each bucket
for (int p=0; p<6; p++)
{ spots[spot].l[p]=0;
spots[spot].r[p]=0;
for (int i=0; i<bwidth; i++)
{ int b = boff+p*bwidth+i;
spots[spot].l[p] += X[0][b].Mod()/sqrtnpoints/400;
spots[spot].r[p] += X[1][b].Mod()/sqrtnpoints/400;
}
if (spots[spot].l[p]!=0) spots[spot].l[p] = sqrt(spots[spot].l[p])*100;
if (spots[spot].r[p]!=0) spots[spot].r[p] = sqrt(spots[spot].r[p])*100;
}
}
if (ExportCancelled) return 0;
//
// Now we have spots.l[] and spots.r[] as the raw bucketed output of FFT.
// We will do another pass now to establish maximums and minimums,
// and to rescale l[] and r[] as fractions within that range
double min[6], max[6]; for (int i=0; i<6; i++) {min[i]=500; max[i]=1800+i*100;}
// we will in fact start fifteen seconds into the music, work backwards to
// the start, so setting up decent min/maxes. Then we'll work forwards through the piece.
int startspot=15000/41; if (startspot>=totspots) startspot=totspots-1; startspot=-startspot;
for (int ispot=startspot; ispot<totspots; ispot++)
{ int spot=ispot; if (spot<0) spot=-ispot;
double *l=&spots[spot].l[0], *r=&spots[spot].r[0];
// fade the max and min
bool adjust = ((spot%2)==0);
for (int p=0; adjust && p<6; p++)
{ max[p]*=0.999;
if (min[p]<22) min[p]=22; min[p]=min[p]+1*1.002;
}
// push out the max and min if we've exceeded them
for (int p=0; p<6; p++)
{ if (l[p]>max[p]) max[p]=l[p];
if (r[p]>max[p]) max[p]=r[p];
if (adjust && (l[p]<min[p] || r[p]<min[p])) min[p]*=0.9;
}
// finally, on the forward pass, write the data
if (ispot>=0)
{ for (int i=0; i<6; i++)
{ spots[spot].min[i] = min[i];
spots[spot].max[i] = max[i];
spots[spot].l[i] = (l[i]-min[i])/(max[i]-min[i]);
spots[spot].r[i] = (r[i]-min[i])/(max[i]-min[i]);
}
}
}
//
return totspots;
}
void TEditor::FileExport()
{
#ifdef __BORLANDC__
_control87(MCW_EM, MCW_EM); // reprogram the FPU so it doesn't raise exceptions
#endif
char fn[MAX_PATH];
OPENFILENAME ofn; ZeroMemory(&ofn,sizeof(ofn)); ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=mhwnd;
ofn.lpstrFilter="AVI files\0*.avi\0\0";
ofn.nFilterIndex=0;
string root = ExtractFilePath(exportfn); ofn.lpstrInitialDir=root.c_str();
ofn.lpstrFile=fn; if (strcmp(curfile,"")==0) *fn=0; else strcpy(fn,stk::ChangeFileExt(stk::ExtractFileName(curfile),"").c_str());
ofn.nMaxFile=MAX_PATH;
ofn.lpstrFileTitle=NULL;
ofn.Flags=OFN_OVERWRITEPROMPT|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
ofn.lpstrDefExt="stk";
BOOL res=GetSaveFileName(&ofn);
if (!res) return;
exportfn = string(fn);
//
int res2 = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_EXPORT),mhwnd,ExportDlgProc, (LPARAM)this);
if (res2!=IDOK) return;
RegSaveUser();
//
ExportCancelled=false; ExportTerminated=false;
mode = mExporting;
SetCursor();
HMENU hmenu = GetMenu(mhwnd);
HMENU hfile = GetSubMenu(hmenu,0);
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi); mi.fMask=MIIM_STRING;
mi.dwTypeData="Cancel &Export"; mi.cch=strlen(mi.dwTypeData);
SetMenuItemInfo(hfile,ID_FILE_EXPORTAVI,FALSE,&mi);
//
HDC sdc=GetDC(0); HDC hdc=CreateCompatibleDC(sdc); ReleaseDC(0,sdc);
BITMAPINFOHEADER bih; ZeroMemory(&bih,sizeof(bih));
bih.biSize=sizeof(bih);
bih.biWidth=exportw;
bih.biHeight=exporth;
bih.biPlanes=1;
bih.biBitCount=24;
bih.biCompression=BI_RGB;
bih.biSizeImage = ((bih.biWidth*bih.biBitCount/8+3)&0xFFFFFFFC)*bih.biHeight;
bih.biXPelsPerMeter=10000;
bih.biYPelsPerMeter=10000;
bih.biClrUsed=0;
bih.biClrImportant=0;
void *bits; HBITMAP hbm=CreateDIBSection(hdc,(BITMAPINFO*)&bih,DIB_RGB_COLORS,&bits,NULL,NULL);
HBITMAP hold=(HBITMAP)SelectObject(hdc,hbm);
int exportinterval=1; if (exportfps!=0) exportinterval = 1000/exportfps;
// load up the stuff we'll need: temporary copy of the current body, and the wav file.
list<string> proclist; list<TBody*> bodies; vector<TPre> sticks;
if (exportproc)
{ proclist = StringToList(exportfigs);
DirScan(sticks,GetStickDir()+"\\");
}
else
{ char tdir[MAX_PATH]; GetTempPath(MAX_PATH,tdir);
char tfn[MAX_PATH]; GetTempFileName(tdir,"stk",0,tfn);
SaveBody(body,tfn); char err[1000];
TBody *b = new TBody(); LoadBody(&b,tfn,err,lbForUse);
DeleteFile(tfn);
bodies.push_back(b);
}
char *wavbuf=0; WavChunk *wav=0; WAVEFORMATEX wfx; TSpot *spots=0; int totspots=0;
int curtune=exporttune;
unsigned long curendtime = exporttime;
unsigned long totsamples=0;
if (exporttune==2)
{ HANDLE hf = CreateFile(exportwav.c_str(),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
if (hf==NULL) {curtune=0; string err="Unable to open file "+ExtractFileName(exportwav); MessageBox(mhwnd,err.c_str(),"Export",MB_OK|MB_ICONERROR);}
else
{ string msg = "Loading music..."; ShowHint(msg); PumpMessages();
DWORD size=GetFileSize(hf,NULL);
wavbuf = new char[size];
DWORD red; ReadFile(hf,wavbuf,size,&red,NULL);
CloseHandle(hf);
wav = (WavChunk*)wavbuf;
ZeroMemory(&wfx,sizeof(wfx));
wfx.cbSize=0;
wfx.nAvgBytesPerSec=wav->fmt.dwAvgBytesPerSec;
wfx.nBlockAlign=wav->fmt.wBlockAlign;
wfx.nChannels=wav->fmt.wChannels;
wfx.nSamplesPerSec=wav->fmt.dwSamplesPerSec;
wfx.wBitsPerSample=wav->fmt.wBitsPerSample;
wfx.wFormatTag=wav->fmt.wFormatTag;
int bytespersample = wfx.nChannels*wfx.wBitsPerSample/8;
totsamples = wav->dat.size/bytespersample;
unsigned long bytespersec = wav->fmt.dwSamplesPerSec * wav->fmt.wBitsPerSample/8 * wav->fmt.wChannels;
if (!exporttimefixed) curendtime = (unsigned long)(((double)wav->dat.size)*1000.0 / ((double)bytespersec));
}
}
unsigned long silentindex=0, silentmax=0, silentoffset=0; // if we're doing silent dancing, this is it
if (curtune==0)
{ silentindex=rand()%3;
silentmax=samplesize[silentindex];
silentoffset=rand()%silentmax;
}
HAVI avi = CreateAvi(exportfn.c_str(),exportinterval,curtune==2?&wfx:0);
if (exportcompress)
{ AVICOMPRESSOPTIONS opts; ZeroMemory(&opts,sizeof(opts));
opts.fccHandler = exportopt;
if (exportopt!=0) opts.dwFlags = AVICOMPRESSF_VALID;
HRESULT hr = SetAviVideoCompression(avi,hbm,&opts,true,mhwnd);
if (hr==AVIERR_OK) exportopt = opts.fccHandler;
else ExportCancelled=true;
}
if (curtune==2 && !ExportCancelled)
{ totspots = fft(wav,NULL,0);
spots = new TSpot[totspots];
fft(wav,spots,totspots);
}
//
unsigned long nframe=0, nsample=0;
unsigned long totbytes=0;
int procoff=exportw-exporth; if (procoff<0) procoff=0; int procgap=exporth/3;
//
for (unsigned long time=0; time<=curendtime && !ExportCancelled; time+=exportinterval)
{ // Let's add more bodies into the procession, if needed.
// procoff is how many pixels the first body starts from the left of the bitmap.
if (exportproc)
{ while (procoff<=-exporth-procgap)
{ TBody *b=bodies.front(); bodies.pop_front(); delete b;
procoff+=exporth+procgap;
}
while (procoff + (int)bodies.size()*(exporth+procgap) < exportw)
{ for (list<string>::const_iterator ip=proclist.begin(); ip!=proclist.end(); ip++)
{ int i = ChooseRandomBody(reggarble(*ip),sticks,"");
string fn = sticks[i].path;
TBody *b = new TBody(); char err[1000];
LoadBody(&b,fn.c_str(),err,lbForUse);
bodies.push_back(b);
}
}
}
// first, if necessary, we add up to "<time" of music to the stream
// (i.e. there'll be nothing on the first time round this loop
if (curtune==2)
{ unsigned long tosample = (unsigned long)(((double)wfx.nSamplesPerSec)*((double)time)/1000.0);
if (tosample>totsamples) tosample=totsamples; // in case of any rounding errors!
unsigned long numbytes = (tosample-nsample)*wfx.wBitsPerSample/8*wfx.nChannels;
unsigned long curbyte = nsample*wfx.wBitsPerSample/8*wfx.nChannels;
if (numbytes>0) AddAviAudio(avi, wav->dat.data+curbyte, numbytes);
totbytes += numbytes;
nsample=tosample;
}
// second, we calculate the frequencies
double freq[3][6];
if (curtune==0)
{ unsigned int off = ((silentoffset+time)/41)%silentmax;
unsigned char *sd = sampledat[silentindex]+off*12;
for (int chan=0; chan<2; chan++)
{ for (int band=0; band<6; band++)
{ unsigned char s = sd[chan*6+band];
double d = ((double)s)/255.0;
freq[chan][band]=d;
}
}
for (int band=0; band<6; band++) {freq[2][0]=freq[0][3]; freq[2][1]=freq[1][4];}
}
else if (curtune==1)
{ for (int chan=0; chan<3; chan++)
{ for (int band=0; band<6; band++)
{ freq[chan][band] = ((double)(rand()%1000))/1000.0;
}
}
}
else if (curtune==2)
{ int spot = time/41;
for (int band=0; band<6; band++)
{ freq[0][band] = spots[spot].l[band];
freq[1][band] = spots[spot].r[band];
}
freq[2][0]=spots[spot].l[3]; freq[2][1]=spots[spot].r[4];
}
// now assign that into the bodies
double cmul=((double)exportinterval)/10.0; // 10ms is notional standard interval
for (list<TBody*>::const_iterator ib=bodies.begin(); ib!=bodies.end(); ib++)
{ TBody *b = *ib;
b->AssignFreq(freq,cmul);
b->Recalc(); b->RecalcEffects(true);
}
// and draw them!
if (exportproc)
{ RECT rc; rc.left=0; rc.top=0; rc.right=exportw; rc.bottom=exporth;
FillRect(hdc,&rc,(HBRUSH)GetStockObject(BLACK_BRUSH));
int x=procoff; list<TBody*>::const_iterator ib=bodies.begin();
for (; x<exportw; ib++)
{ TBody *b = *ib;
rc.left=x; rc.top=0; rc.right=x+exporth; rc.bottom=exporth;
SimpleDraw(hdc,rc,b);
x+=exporth+procgap;
}
procoff -= exportw*exportinterval/exportproctime;
}
else
{ TBody *b = bodies.front();
RECT rc; rc.left=0; rc.top=0; rc.right=exportw; rc.bottom=exporth;
SimpleDraw(hdc,rc,b);
}
if (!ExportCancelled)
{ AddAviFrame(avi,hbm); nframe++;
string msg = "Exporting: "+StringFrac(((double)time)*100.0/((double)curendtime)); ShowHint(msg);
PumpMessages();
}
}
CloseAvi(avi);
for (list<TBody*>::const_iterator i=bodies.begin(); i!=bodies.end(); i++)
{ TBody *b = *i;
delete b;
}
if (wavbuf!=0) delete[] wavbuf;
if (spots!=0) delete[] spots;
SelectObject(hdc,hold);
DeleteObject(hbm);
DeleteObject(hdc);
mi.dwTypeData="&Export AVI..."; mi.cch=strlen(mi.dwTypeData);
SetMenuItemInfo(hfile,ID_FILE_EXPORTAVI,FALSE,&mi);
mode=mNothing;
string msg;
if (ExportCancelled) msg="Cancelled export.";
else msg="Exported file "+ChangeFileExt(ExtractFileName(exportfn),"");
ShowHint(msg);
SetCursor();
if (ExportTerminated) PostMessage(mhwnd,WM_CLOSE,0,0);
return;
}
void TEditor::HoverMonitor(int x,int y)
{ // First see if a movement has caused us to display something new
ThisHover = PointAtCoords(x,y,true);
if (hit.n!=-1 && ThisHover.n==body->limbs[hit.n].root && ThisHover.type==htSpot)
{ ThisHover.n=hit.n;
ThisHover.type=htRoot;
}
if (ThisHover.n!=LastHover.n || ThisHover.type!=LastHover.type || ThisHover.s!=LastHover.s)
{ ShowHint("");
LastHover=ThisHover;
return;
}
// Otherwise, see if the end of timer means that something else should be displayed
if (IsHoverTimer)
{ if (GetTickCount()>EndHoverTimer)
{ ShowHint(""); IsHoverTimer=false;
}
}
}
void TEditor::SetCursor()
{ int c=0;
const int cpoint=7, cmove=1, croot=2, cangle=3, ccre=4, ccreate=5, czoom=6, chourglass=-1;
//
if (mode==mNodePressing && tool==tCreate) c=ccreate;
else if (mode==mNodePressing && tool==tEdit) c=cmove;
else if (mode==mShapeLinePressing) c=ccreate;
else if (mode==mShapeSpotPressing) c=cmove;
else if (mode==mCreateDragging) c=ccreate;
else if (mode==mNodeMoving) c=cmove;
else if (mode==mAoffDragging) c=cangle;
else if (mode==mAscaleDragging) c=cangle;
else if (mode==mLminDragging) c=cangle;
else if (mode==mLmaxDragging) c=cangle;
else if (mode==mNothingTesting) c=0;
else if (mode==mZoomDragging) c=czoom;
else if (mode==mExporting) c=chourglass;
//
else if (tool==tCreate)
{ if (ThisHover.s!=-1 && ThisHover.n==-1)
{ if (hit.s==ThisHover.s && hit.n==-1 && ThisHover.type==htSpot) c=cmove;
else if (hit.s==ThisHover.s && hit.n==-1 && ThisHover.type==htAroot) c=cmove;
else if (hit.s==ThisHover.s && hit.n==-1 && ThisHover.type==htLine) c=ccreate;
else c=croot;
}
else if (ThisHover.n==-1/*background*/) c=ccre;
else if (ThisHover.type==htSpot) c=ccreate;
else if (ThisHover.type==htAroot) c=ccre;
else if (ThisHover.type==htAmin) c=cangle;
else if (ThisHover.type==htAmax) c=cangle;
else if (ThisHover.type==htLine) c=cmove;
else if (ThisHover.type==htRoot) c=ccreate;
else if (ThisHover.type==htPie) c=ccre;
}
else if (tool==tEdit)
{ if (ThisHover.s!=-1 && ThisHover.n==-1)
{ if (hit.s==ThisHover.s && hit.n==-1 && ThisHover.type==htSpot) c=cmove;
else if (hit.s==ThisHover.s && hit.n==-1 && ThisHover.type==htAroot) c=cmove;
else c=croot;
}
else if (ThisHover.n==-1/*background*/) c=cpoint;
else if (ThisHover.type==htSpot) c=cmove;
else if (ThisHover.type==htAmin) c=cangle;
else if (ThisHover.type==htAmax) c=cangle;
else if (ThisHover.type==htLine) c=cmove;
else if (ThisHover.type==htRoot && body->limbs[ThisHover.n].root!=0) c=croot;
else if (ThisHover.type==htRoot && body->limbs[ThisHover.n].root==0) c=cmove;
else if (ThisHover.type==htPie) c=cpoint;
}
else if (tool==tZoom)
{ c=czoom;
}
HCURSOR hc; if (c==0) hc=LoadCursor(NULL,IDC_ARROW);
else if (c==chourglass) hc=LoadCursor(NULL,IDC_WAIT);
else hc=hCursor[c];
::SetCursor(hc);
}
char *SelectHint(int n,char *a,char *b)
{ if ((rand()%n)==0) return b; else return a;
}
void TEditor::ShowHint(string msg)
{ // Maybe we're being asked to override...
if (msg!="")
{ SendMessage(hstatwnd,SB_SETTEXT,255|SBT_NOBORDERS,(LPARAM)msg.c_str());
IsHoverTimer=true;
EndHoverTimer=GetTickCount()+2000;
return;
}
// or merely to display whatever's appropiate at this new stage
const char *c="Right-click on background to change editing mode";
//
// We'll first see if there's a specific mode for the current. If not, we'll see
// what's hovering on
if (mode==mNodePressing && tool==tCreate) c="Click and drag to create a new line out of a joint";
else if (mode==mNodePressing && tool==tEdit) c="Click and drag to move this joint";
else if (mode==mCreateDragging) c="Left-click and drag to create a new line";
else if (mode==mNodeMoving) c=SelectHint(3,"Click and drag to move this joint","Click and drag. (SHIFT to stop snapping)");
else if (mode==mAoffDragging) c=SelectHint(3,"Drag minimum range of motion","Drag minimum. (SHIFT to stop snapping)");
else if (mode==mAscaleDragging) c=SelectHint(3,"Drag maximum range of motion","Drag maximum. (SHIFT to stop snapping)");
else if (mode==mLminDragging) c="Drag maximum range of motion";
else if (mode==mLmaxDragging) c="Drag minimum range of motion";
else if (mode==mNothingTesting) c="Click to stop animation";
else if (mode==mZoomDragging) c="Zoom in...";
//
else if (tool==tCreate)
{ if (ThisHover.s!=-1 && ThisHover.n==-1) // a shape
{ if (ThisHover.type==htLine) c="CREATE mode. Click and drag to create a new corner here";
else if (ThisHover.type==htSpot) c="Click and drag to move this corner";
else if (ThisHover.type==htShape) c="CREATE mode. Click and drag on a line to create a new corner on it";
}
else if (ThisHover.n==-1/*background*/) c=SelectHint(3,"CREATE mode. Click and drag to create a new line out of a joint","CREATE mode. (Right-click to go back to EDIT mode)");
else if (ThisHover.type==htSpot) c="Click and drag to create a new line from this joint";
else if (ThisHover.type==htAmin) c="Drag minimum range of motion";
else if (ThisHover.type==htAmax) c="Drag maximum range of motion";
else if (ThisHover.type==htLine) c="Click to select this line";
else if (ThisHover.type==htRoot) c="Click and drag to create a new line from this joint";
else if (ThisHover.type==htPie)
{ char d[200]; int ic=body->limbs[ThisHover.n].chan, ib=body->limbs[ThisHover.n].band;
if (ic==2) wsprintf(d,"[freq=diff%i] ",ib+1);
else if (ic==3) wsprintf(d,"[freq=karaoke%i] ",ib+1);
else if (ic==0) wsprintf(d,"[freq=left%i] ",ib+1);
else if (ic==1) wsprintf(d,"[freq=right%i] ",ib+1);
else if (ic==4) wsprintf(d,"[freq=fixed] ");
else *d=0;
msg = string(d)+"Right-click to respond to different frequency";
c = msg.c_str();
}
}
else if (tool==tEdit)
{ if (ThisHover.s!=-1 && ThisHover.n==-1) // a shape
{ if (ThisHover.type==htLine) c="Click to select the outline of this shape";
else if (ThisHover.type==htSpot) c="Click and drag to move this corner";
else if (ThisHover.type==htShape) c="EDIT mode. Click to select this shape";
}
else if (ThisHover.n==-1 /*background*/) c=SelectHint(4,"EDIT mode. Click on a joint to move it","EDIT mode. Right-click on background to change mode");
else if (ThisHover.type==htSpot)
{ if (body->limbs[ThisHover.n].anchor==0) c=SelectHint(3,"Click and drag to move this joint","Right-click to anchor this joint");
else c="Right-click to anchor this joint";
}
else if (ThisHover.type==htAmin) c="Drag minimum range of motion";
else if (ThisHover.type==htAmax) c="Drag maximum range of motion";
else if (ThisHover.type==htLine) c="Click to select this line";
else if (ThisHover.type==htRoot && body->limbs[ThisHover.n].root!=0)
{ if (body->limbs[ThisHover.n].aisoff)
{ c="Relative angle. Left-click to make it an absolute angle";
}
else
{ c="Absolute angle. Left-click to make it a relative angle";
}
}
else if (ThisHover.type==htPie)
{ char d[200]; int ic=body->limbs[ThisHover.n].chan, ib=body->limbs[ThisHover.n].band;
if (ic==4) wsprintf(d,"[freq=fixed] ");
else if (ic==3) wsprintf(d,"[freq=karaoke%i] ",ib+1);
else if (ic==2) wsprintf(d,"[freq=diff%i] ",ib+1);
else if (ic==1) wsprintf(d,"[freq=right%i] ",ib+1);
else if (ic==0) wsprintf(d,"[freq=left%i] ",ib+1);
else *d=0;
msg = string(d)+"Right-click to respond to different frequency";
c = msg.c_str();
}
}
else if (tool==tZoom)
{ c="ZOOM mode. Drag a rectangle to zoom in; click to zoom out";
}
SendMessage(hstatwnd,SB_SETTEXT,255|SBT_NOBORDERS,(LPARAM)c);
}
void TEditor::ShowTitle()
{ string s = stk::ChangeFileExt(stk::ExtractFileName(curfile),"")+" - Sticky";
if (strcmp(curfile,"")==0) s="Sticky";
SetWindowText(mhwnd,s.c_str());
}
void TEditor::FileOpen(char *afn)
{ if (!FileClose()) return;
char fn[MAX_PATH];
if (afn!=NULL && strcmp(afn,"")!=0) strcpy(fn,afn);
else
{ OPENFILENAME ofn; ZeroMemory(&ofn,sizeof(ofn)); ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=mhwnd;
ofn.lpstrFilter="Sticks\0*.stk\0\0";
ofn.nFilterIndex=0;
ofn.lpstrFile=fn; strcpy(fn,"");
ofn.nMaxFile=MAX_PATH;
ofn.lpstrFileTitle=NULL;
string root = GetStickDir();
ofn.lpstrInitialDir=root.c_str();
ofn.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
ofn.lpstrDefExt="stk";
BOOL res=GetOpenFileName(&ofn);
if (!res) return;
}
char err[1000];
bool res=LoadBody(&body,fn,err,lbForEditing);
if (!res) {MessageBox(mhwnd,err,"Error opening file",MB_OK);return;}
strcpy(curfile,fn); ismodified=false; ShowTitle();
tool=tEdit;
FileReady();
string msg = "Opened file "+stk::ChangeFileExt(stk::ExtractFileName(fn),""); ShowHint(msg);
}
void TEditor::FileNew()
{ if (!FileClose()) return;
body->NewFile();
strcpy(curfile,""); ismodified=false;
ShowJoints=true; ShowAngles=true; ShowInvisibles=true;
tool=tCreate;
FileReady();
ShowHint("CREATE mode. To create a new line, click+drag on a joint.");
}
void TEditor::FileReady()
{ mode=mNothing; hit.n=-1; hit.s=-1; cori=-1; hit.type=htMiss;
sellimbs.clear(); selshapes.clear();
zoom=30; offx=0; offy=0;
nextchan=0; nextband=0; nextlinestyle=""; nextfreqstyle=""; nextfillstyle="";
for (list<TUndoData>::iterator i=undos.begin(); i!=undos.end(); i++) i->releasebmps();
frees.splice(frees.end(),undos); undopos=-1;
fnbackdrop=RecallBack(curfile); Backdrop(fnbackdrop,true);
ismodified=false;
isready=true;
Recalc(0);
ShowTitle();
UpdateMenus();
SetScrollBars();
Redraw(); SetCursor();
}
bool TEditor::FileClose()
{ if (ismodified)
{ string s = "Do you want to save the changes you made to ";
if (strcmp(curfile,"")==0) s+="[untitled]"; else s+=stk::ChangeFileExt(stk::ExtractFileName(curfile),"");;
s+="?";
int res=MessageBox(mhwnd,s.c_str(),"Sticky",MB_YESNOCANCEL);
if (res==IDCANCEL) return false;
if (res==IDYES)
{ bool bres=FileSave();
if (!bres) return false;
}
}
for (list<TUndoData>::iterator i=undos.begin(); i!=undos.end(); i++) i->releasebmps();
frees.splice(frees.end(),undos); undopos=-1;
return true;
}
typedef struct {int numrot; TEditor *editor;} TRotDlgDat;
int WINAPI UprightDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ TRotDlgDat *dat;
#pragma warning( push )
#pragma warning( disable : 4244 4312 )
if (msg==WM_INITDIALOG) {SetWindowLongPtr(hdlg,DWLP_USER,lParam); dat=(TRotDlgDat*)lParam;}
else {dat=(TRotDlgDat*)GetWindowLongPtr(hdlg,DWLP_USER);}
#pragma warning( pop )
if (dat==NULL) return FALSE;
TEditor *editor = dat->editor;
//
switch (msg)
{ case WM_INITDIALOG:
{ CheckDlgButton(hdlg,IDC_ALWAYSCHECK,UserCheckUpright?BST_CHECKED:BST_UNCHECKED);
} // and fall through to the rest of the stuff...
case WM_APP:
{ char c[1000]; wsprintf(c,"The stick figure currently contains %i non-upright bitmaps.",dat->numrot);
SetDlgItemText(hdlg,IDC_UPRIGHTREPORT,c);
EnableWindow(GetDlgItem(hdlg,IDC_FIX),(dat->numrot==0)?FALSE:TRUE);
return TRUE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (id==IDOK) UserCheckUpright=(IsDlgButtonChecked(hdlg,IDC_ALWAYSCHECK)==BST_CHECKED);
if (id==IDOK || id==IDCANCEL) EndDialog(hdlg,id);
if (id==IDC_FIX && code==BN_CLICKED)
{ editor->FixUpright();
dat->numrot=0;
SendMessage(hdlg,WM_APP,0,0);
}
return TRUE;
}
}
return FALSE;
}
bool TEditor::MaybeCheckUpright(bool forcedialog)
{ if (!UserCheckUpright && !forcedialog) return true;
int numrot=0;
for (int si=0; si<(int)body->shapes.size(); si++)
{ int li=circlelimb_from_shape(si);
if (body->shapes[si].brush.type==ctBitmap && li!=-1)
{ TLimb &limb = body->limbs[li];
bool norot = (!limb.aisoff && limb.chan==4 && limb.band==0 && limb.aoff==0 && limb.aspring==0);
if (!norot) numrot++;
}
}
if (!forcedialog && numrot==0) return true;
TRotDlgDat dat; dat.numrot=numrot; dat.editor=this;
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_UPRIGHT),mhwnd,UprightDlgProc,(LPARAM)&dat);
return (res==IDOK);
}
void TEditor::FixUpright()
{ MarkUndo();
for (int si=0; si<(int)body->shapes.size(); si++)
{ int li=circlelimb_from_shape(si);
if (body->shapes[si].brush.type==ctBitmap && li!=-1)
{ TLimb &limb = body->limbs[li];
limb.aisoff=false;
limb.aoff=0; limb.aspring=0;
limb.chan=4; limb.band=0;
}
}
ismodified=true;
Recalc(0);
Redraw(); SetCursor();
}
void TEditor::GetRootLimbsOfSellimbs(list<int> *roots)
{ vector<bool> sbitmap; sbitmap.resize(body->nlimbs);
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++) sbitmap[*i]=true;
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ int limb = *i; limb=body->limbs[limb].root;
while (limb!=0 && !sbitmap[limb]) limb=body->limbs[limb].root;
if (limb==0) roots->push_back(*i);
}
}
bool TEditor::GetRootLimbsOfSelection(list<int> *roots)
{ // This routine is specifically designed for "copy". It gives an answer
// that includes all selected limbs, and also all "feasible" shapes.
// What is a feasible shape? -- well, intuitively, if you try to copy
// a shape which spans two massive great trees, you shouldn't be able to,
// since that would involve copying the two trees. But if you merely copy
// a shape that's quite self-contained, then you should.
// Thus: each shape i marks each of its limbs with a soft i.
// No soft i can contribute more than once to the list of roots.
// Therefore: if a shape is self-contained, it will have only one soft i root,
// but if it's spread out it would have two or more,
// but if it's spread out and the things were already hard-rooted, that'll be okay.
if (roots!=NULL) roots->clear();
if (selshapes.size()==0 && sellimbs.size()==1) {if (roots!=NULL) roots->push_back(sellimbs.front()); return true;}
if (selshapes.size()==0 && sellimbs.size()==0) return false;
//
// First we mark the soft i's, and the hard i's with -1
vector<int> bsel; bsel.resize(body->nlimbs,0);
list<int> lsel;
int ssi=0; for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++,ssi++)
{ stk::TShape &shape = body->shapes[*i];
for (vector<TJointRef>::const_iterator j=shape.p.begin(); j!=shape.p.end(); j++)
{ bsel[j->i]=ssi+1; lsel.push_back(j->i);
}
}
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ bsel[*i]=-1; lsel.push_back(*i);
}
lsel.sort(); lsel.unique();
// now bsel is a bitmap of the selected limbs, and lsel is a list of the
// limbs which we must account for.
// Algorithm: for each limb we're intersted in, work towards the root, and mark
// its rooties ancestor that was also in the list.
vector<bool> gotsofts; gotsofts.resize(selshapes.size()+1,false);
list<int> hroots;
for (list<int>::const_iterator i=lsel.begin(); i!=lsel.end(); i++)
{ int limb=*i, aroot=limb;
while (body->limbs[limb].root!=0)
{ limb=body->limbs[limb].root;
if (bsel[limb]!=0) aroot=limb;
}
hroots.push_back(aroot);
int type = bsel[aroot];
LUASSERT(type!=0);
if (type>0)
{ if (gotsofts[type]) return false; // too bad... this softi was already being used as a root elsewhere
gotsofts[type]=true; bsel[aroot]=-1; // since we've opted for this, others can also use it
// without them having to count against the softi budget as well.
}
}
// done!
hroots.sort(); hroots.unique();
if (roots!=NULL) *roots = hroots;
return true;
}
void TEditor::UpdateMenus()
{ //InvalidateRect(hdb,NULL,TRUE);
HMENU hmenu = GetMenu(mhwnd);
HMENU hed = GetSubMenu(hmenu,1);
bool canstretch = (sellimbs.size()>0 || selshapes.size()==0); // either nothing, or some limbs
EnableMenuItem(hed,ID_EDIT_ENLARGE,canstretch?MF_ENABLED:MF_GRAYED);
EnableMenuItem(hed,ID_EDIT_SHRINK,canstretch?MF_ENABLED:MF_GRAYED);
EnableMenuItem(hed,ID_EDIT_REDO,MF_BYCOMMAND|(undopos==-1?MF_GRAYED:MF_ENABLED));
bool canundo=false; if (undopos==-1 && undos.size()>0) canundo=true;
if (undopos!=-1 && undopos+2<(int)undos.size()) canundo=true; // if we've reached the end
EnableMenuItem(hed,ID_EDIT_UNDO,MF_BYCOMMAND|(canundo?MF_ENABLED:MF_GRAYED));
//int r = GetRootLimbOfSelection();
bool cancopy = GetRootLimbsOfSelection(NULL);
EnableMenuItem(hed,ID_EDIT_CUT,MF_BYCOMMAND|(cancopy?MF_ENABLED:MF_GRAYED));
EnableMenuItem(hed,ID_EDIT_COPY,MF_BYCOMMAND|(cancopy?MF_ENABLED:MF_GRAYED));
bool canpaste=false;
if (sellimbs.size()==0 && selshapes.size()==0) canpaste=true; // paste to the root
if (sellimbs.size()==1) canpaste=true;
EnableMenuItem(hed,ID_EDIT_PASTE,MF_BYCOMMAND|(!canpaste?MF_GRAYED:MF_ENABLED));
EnableMenuItem(hed,ID_EDIT_INSERT,MF_BYCOMMAND|(!canpaste?MF_GRAYED:MF_ENABLED));
EnableMenuItem(hed,ID_EDIT_FLIP,MF_BYCOMMAND|(sellimbs.size()==0?MF_GRAYED:MF_ENABLED));
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi); mi.fMask=MIIM_STRING|MIIM_STATE; mi.fType=MFT_STRING;
if (sellimbs.size()==0 && selshapes.size()==0) {mi.fState=MFS_DISABLED; mi.dwTypeData="&Delete line\tDel"; mi.cch=strlen(mi.dwTypeData);}
else if (sellimbs.size()!=0 && selshapes.size()==0) {mi.fState=MFS_ENABLED; mi.dwTypeData="&Delete line\tDel"; mi.cch=strlen(mi.dwTypeData);}
else if (sellimbs.size()==0 && selshapes.size()!=0) {mi.fState=MFS_ENABLED; mi.dwTypeData="&Delete shape\tDel"; mi.cch=strlen(mi.dwTypeData);}
else if (sellimbs.size()!=0 && selshapes.size()!=0) {mi.fState=MFS_ENABLED; mi.dwTypeData="&Delete\tDel"; mi.cch=strlen(mi.dwTypeData);}
SetMenuItemInfo(hed,ID_EDIT_DELETE,FALSE,&mi);
HMENU ht = GetSubMenu(hmenu,2);
CheckMenuItem(ht,ID_TOOLS_TEST,MF_BYCOMMAND|(mode==mNothingTesting?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_SHOWANGLES,MF_BYCOMMAND|(ShowAngles?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_SHOWJOINTS,MF_BYCOMMAND|(ShowJoints?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_SHOWINVISIBLES,MF_BYCOMMAND|(ShowInvisibles?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_ZOOMMODE,MF_BYCOMMAND|(tool==tZoom?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_EDITMODE,MF_BYCOMMAND|(tool==tEdit?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_CREATEMODE,MF_BYCOMMAND|(tool==tCreate?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_SNAP,MF_BYCOMMAND|(UserSnap?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_TOOLS_GRID,MF_BYCOMMAND|(UserGrid?MF_CHECKED:MF_UNCHECKED));
CheckMenuItem(ht,ID_INVERT,MF_BYCOMMAND|(WhitePrint?MF_CHECKED:MF_UNCHECKED));
//
ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
mi.fMask=MIIM_DATA|MIIM_STATE|MIIM_TYPE;
mi.fType=MFT_STRING; const char *c="&Template"; if (hbackdrop==0) c="&Template...";
mi.fState=MFS_ENABLED; if (hbackdrop!=0) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)c; mi.cch=strlen(c);
SetMenuItemInfo(ht,ID_TOOLS_BACKDROP,FALSE,&mi);
}
void im(HMENU hmenu,const string s,int id=0,bool checked=false,bool enabled=true,bool radio=true)
{ MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
if (s=="--")
{ mi.fMask=MIIM_TYPE|MIIM_ID;
mi.fType=MFT_SEPARATOR; mi.wID=0;
InsertMenuItem(hmenu,0,TRUE,&mi);
return;
}
mi.fMask=MIIM_TYPE|MIIM_ID|MIIM_STATE|MIIM_DATA;
mi.fType=MFT_STRING; if (radio) mi.fType|=MFT_RADIOCHECK;
mi.wID = id;
mi.fState=enabled?MFS_ENABLED:MFS_GRAYED; if (checked) mi.fState|=MFS_CHECKED;
mi.dwTypeData = (char*)s.c_str(); mi.cch=s.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
}
void im(HMENU hmenu,const string s,HMENU hsubmenu)
{ MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
mi.fMask=MIIM_TYPE|MIIM_STATE|MIIM_ID|MIIM_DATA|MIIM_SUBMENU;
mi.fType=MFT_STRING;
mi.fState=MFS_ENABLED;
mi.wID = 0;
mi.dwTypeData=(char*)s.c_str(); mi.cch=s.length();
mi.hSubMenu = hsubmenu;
InsertMenuItem(hmenu,0,TRUE,&mi);
}
void im(HMENU hmenu,TBody *body, int idfirst,bool keyboard,string selstyle)
{ MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
mi.fMask=MIIM_TYPE|MIIM_STATE|MIIM_ID|MIIM_DATA;
mi.fType=MFT_STRING|MFT_RADIOCHECK;
int id=(int)body->styles.size()-1;
for (list<TStyle>::reverse_iterator i=body->styles.rbegin(); i!=body->styles.rend(); i++,id--)
{ string s=i->name;
bool checked = (selstyle==s);
if (keyboard && i->shortcut!=0) {s=s+"\tCtrl+"+string(&i->shortcut,1);}
mi.wID = idfirst+id;
mi.fState=MFS_ENABLED; if (checked) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)s.c_str(); mi.cch=s.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
}
}
enum im_effect_properties {imDefault=0, imDisallowBitmaps=1};
void im(HMENU hmenu,const vector<TEffect> &alleffects, const list<string> effects, bool notalleffect, int idfirst,im_effect_properties props=imDefault)
{ // effects is a list of the effects used in this selection.
// notalleffect shows that some objects in the selection were not effects.
// If they were all effects, and effects.size()==1, then tick it.
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
mi.fMask=MIIM_TYPE|MIIM_STATE|MIIM_ID|MIIM_DATA;
mi.fType=MFT_STRING|MFT_RADIOCHECK;
string def; if (effects.size()==1 && !notalleffect) def=effects.front();
//
int id=idfirst;
for (vector<TEffect>::const_iterator i=alleffects.begin(); i!=alleffects.end(); i++, id++)
{ if (props==imDisallowBitmaps)
{ bool anybitmaps=false;
for (vector<stk::TColor>::const_iterator j=i->cols.begin(); j!=i->cols.end(); j++)
{ if (j->type==ctBitmap) {anybitmaps=true; break;}
}
if (anybitmaps) continue;
}
mi.wID=id;
mi.fState=MFS_ENABLED; if (StringLower(i->name)==StringLower(def)) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)i->name.c_str(); mi.cch=i->name.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
}
}
struct CumInfo
{ CumInfo(double _d, int _r) : d(_d),r(_r) {}
double d; int r;
bool operator< (const CumInfo &b) const {if (d<b.d) return true; if (d>b.d) return false; return r<b.r;}
bool operator== (const CumInfo &b) const {return d==b.d && r==b.r;}
};
void im(HMENU hmenu,const list<CumInfo> cums,int idfirst,vector<CumInfo> &retcums)
{ // cums is the list of all the cums encountered in the selection.
// The cums list is always expected to have something, even if just "0"
// When we create the menu, we place a copy of it in retcums. And each item
// is indexed to its position in retcums. That makes it easy for the caller to
// retrieve the one that was chosen.
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
mi.fMask=MIIM_TYPE|MIIM_STATE|MIIM_ID|MIIM_DATA;
mi.fType=MFT_STRING|MFT_RADIOCHECK;
bool def=false; double ddef=0; int rdef=0;
if (cums.size()==1) {def=true; ddef=cums.front().d; rdef=cums.front().r; rdef*=rdef;}
// rdef may be -1 or 0 or 1. We convert to 0/1 here for convenience.
int id=idfirst;
retcums.clear();
//
// We will put into the menu all usercums. Then, as rate() or fixedrate(), anything
// listed but not in usercums.
for (list<CumInfo>::const_iterator j=cums.begin(); j!=cums.end(); j++)
{ double d=j->d; int dr=j->r; dr*=dr;
bool wasinusercums=false;
for (list<TUserCum>::const_iterator i=usercums.begin(); i!=usercums.end() && !wasinusercums; i++)
{ double aa=d, ab=i->r;
bool ba=i->reflect, bb=(dr!=0);
if (aa==ab && ((ba&&bb)||(!ba&&!bb))) wasinusercums=true;
}
if (wasinusercums) continue;
string s; if (d<0 && dr==1) s="reflect_fixedrate("+StringFloat(-d)+")";
else if (d<0) s="fixedrate("+StringFloat(-d)+")";
else if (dr==1) s="reflect_rate("+StringFloat(d)+")";
else s="rate("+StringFloat(d)+")";
mi.wID = id;
mi.fState=MFS_ENABLED; if (def && ddef==d && rdef==dr) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)s.c_str(); mi.cch=s.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
retcums.push_back(CumInfo(d,dr)); id++;
}
for (list<TUserCum>::reverse_iterator i=usercums.rbegin(); i!=usercums.rend(); i++)
{ string s = i->name; int ireflect=(i->reflect?1:0);
mi.wID = id;
mi.fState=MFS_ENABLED; if (def && ddef==i->r && rdef==ireflect) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)s.c_str(); mi.cch=s.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
retcums.push_back(CumInfo(i->r,ireflect)); id++;
}
}
void im(HMENU hmenu,const list<COLORREF> cols,bool uncol, int idfirst,bool keyboard,vector<COLORREF> *extracols)
{ // cols is a list of all the colours encountered in the selection.
// uncol is true if the selection also includes an object missing a colour:
// this prevents any tickmark from appearing.
// If cols has size 1, and uncol=false, then only one colour is used in the list, so check it!
// when we create the list, we give indexes 0 <= i< ncols for the standard colours
// and ncols <= i < ncols+usercols for the user-defined colours
// and ncols+usercols <= i < ncols+usercols+extracols for the extra ones.
// We also ensure that 'extracols' contains all these extra colours that we're talking about
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
mi.fMask=MIIM_TYPE|MIIM_STATE|MIIM_ID|MIIM_DATA;
mi.fType=MFT_STRING|MFT_RADIOCHECK;
// dr,dg,db indicate the colour that should have a checkmark on it
int dr=-1,dg=-1,db=-1; if (cols.size()==1 && !uncol) {COLORREF c=cols.front(); dr=GetRValue(c); dg=GetGValue(c); db=GetBValue(c);}
//
// First we'll put in the extracols.
for (list<COLORREF>::const_iterator i=cols.begin(); i!=cols.end(); i++)
{ int id=-1;
int r=GetRValue(*i), g=GetGValue(*i), b=GetBValue(*i);
for (int nc=0; nc<ncols && id==-1; nc++)
{ if (defcols[nc].r==r && defcols[nc].g==g && defcols[nc].b==b) id=nc;
}
int j=0;
for (list<TUserColour>::const_iterator uc=usercols.begin(); uc!=usercols.end() && id==-1; uc++, j++)
{ if (uc->c.r==r && uc->c.g==g && uc->c.b==b) id=j+ncols;
}
for (int ne=0; ne<(int)extracols->size() && id==-1; ne++)
{ COLORREF c=(*extracols)[ne];
if (r==GetRValue(c) && g==GetGValue(c) && b==GetBValue(c)) id=j+ncols+usercols.size()+ne;
}
if (id==-1)
{ id=ncols+usercols.size()+extracols->size();
extracols->push_back(RGB(r,g,b));
}
if (id>=ncols+(int)usercols.size())
{ string s = "RGB("+StringInt(r)+","+StringInt(g)+","+StringInt(b)+")";
mi.wID = idfirst+id;
mi.fState=MFS_ENABLED; if (dr==r && dg==g && db==b) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)s.c_str(); mi.cch=s.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
}
}
//
// Now the usercols
int j=usercols.size()-1;
for (list<TUserColour>::reverse_iterator it=usercols.rbegin(); it!=usercols.rend(); it++,j--)
{ string s=it->name;
int id=ncols+j;
mi.wID = idfirst+id;
mi.fState=MFS_ENABLED; if (dr==it->c.r && dg==it->c.g && db==it->c.b) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)s.c_str(); mi.cch=s.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
}
//
// Now the defcols
char *colkey[2][7]={{"Black\tK","White\tW","Red\tD","Green\tG","Blue\tB","Yellow\tY","Purple\tP"},
{"Black","White","Red","Green","Blue","Yellow","Purple"}};
for (j=ncols-1; j>=0; j--)
{ string s; if (keyboard) s=colkey[0][j]; else s=colkey[1][j];
int id=j;
mi.wID = idfirst+id;
mi.fState=MFS_ENABLED; if (dr==defcols[j].r && dg==defcols[j].g && db==defcols[j].b) mi.fState|=MFS_CHECKED;
mi.dwTypeData=(char*)s.c_str(); mi.cch=s.length();
InsertMenuItem(hmenu,0,TRUE,&mi);
}
}
void BalanceMenu(HMENU hmenu)
{ int n=GetMenuItemCount(hmenu);
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi));
mi.cbSize=sizeof(mi); mi.fMask=MIIM_FTYPE;
for (int i=38; i<n; i+=38)
{ GetMenuItemInfo(hmenu,i,TRUE,&mi);
mi.fType|=MFT_MENUBARBREAK;
SetMenuItemInfo(hmenu,i,TRUE,&mi);
}
}
void TEditor::BackgroundClick(int mx,int my)
{ hit.n=-1; hit.s=-1; mode=mNothing; Redraw(); sellimbs.clear(); selshapes.clear();
//
enum {rmMoreColours=16, rmColourFirst=17, rmColourLast=99,
rmMoreEffects=100,rmEffectsFirst=101, rmEffectsLast=199,
rmZoom=200,rmEdit=201,rmCreate=202};
HMENU hrightmenu=CreatePopupMenu(), hcolmenu=CreatePopupMenu();
vector<COLORREF> extracols; TLimb &limb = body->limbs[0];
// colour menu
list<string> effects; if (limb.color.type==ctEffect) effects.push_back(limb.color.effect);
im(hcolmenu,"Effects...",rmMoreEffects);
im(hcolmenu,body->effects,effects,effects.size()==0,rmEffectsFirst,imDisallowBitmaps);
im(hcolmenu,"--");
list<COLORREF> cols; if (limb.color.type == ctRGB) cols.push_back(RGB(limb.color.rgb.r, limb.color.rgb.g, limb.color.rgb.b));
im(hcolmenu,"Colours...",rmMoreColours);
im(hcolmenu,cols,cols.size()==0,rmColourFirst,false,&extracols);
// background menu
im(hrightmenu,"Background",hcolmenu);
im(hrightmenu,"--");
im(hrightmenu,"Zoom",rmZoom,tool==tZoom);
im(hrightmenu,"Edit",rmEdit,tool==tEdit);
im(hrightmenu,"Create",rmCreate,tool==tCreate);
POINT pt; pt.x=mx; pt.y=my; ClientToScreen(chwnd,&pt);
int cmd=TrackPopupMenu(hrightmenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,chwnd,NULL);
DestroyMenu(hrightmenu);
if (cmd==0) return;
//
if (cmd==rmZoom) {tool=tZoom; ShowHint("");}
else if (cmd==rmEdit) {tool=tEdit; ShowHint("");}
else if (cmd==rmCreate) {tool=tCreate; ShowHint("CREATE mode. Click and drag to create a new line out of a joint");}
else if (cmd==rmMoreColours) UserColours(mhwnd);
else if (cmd==rmMoreEffects) Effects(mhwnd);
else if (cmd>=rmEffectsFirst && cmd<=rmEffectsLast)
{ MarkUndo();
limb.color.type=ctEffect; limb.color.effect=body->effects[cmd-rmEffectsFirst].name;
ismodified=true;
MakeEindexes(body); body->RecalcEffects(true);
Redraw();
}
else if (cmd>=rmColourFirst && cmd<=rmColourLast)
{ MarkUndo(); int r,g,b, c=cmd-rmColourFirst;
if (c<ncols) {r=defcols[c].r; g=defcols[c].g; b=defcols[c].b;}
else if (c<ncols+(int)usercols.size())
{ int ci=ncols; list<TUserColour>::const_iterator ui=usercols.begin();
while (ci<c) {ci++; ui++;}
r=ui->c.r; g=ui->c.g; b=ui->c.b;
}
else
{ int e=c-ncols-(int)usercols.size(); COLORREF cl=extracols[e];
r=GetRValue(cl); g=GetGValue(cl); b=GetBValue(cl);
}
limb.color.rgb.r = r; limb.color.rgb.g = g; limb.color.rgb.b = b; limb.color.type = ctRGB; limb.color.dtype = ctRGB;
WhitePrint=false;
UpdateMenus();
ismodified=true;
Redraw();
}
}
void TEditor::RightClick(int mx,int my)
{ THitTest ht=PointAtCoords(mx,my,true);
if (ht.n<=0 && ht.s==-1) {BackgroundClick(mx,my); return;}
// If a right-click on a selected thing, fine. But if a right-click on
// an unselected thing, then the selection must be removed. Unless shift.
bool isin=false; bool shift = (GetAsyncKeyState(VK_SHIFT)<0);
if (ht.n>0)
{ for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end() && !isin; i++) {if (*i==ht.n) isin=true;}
}
else
{ for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end() && !isin; i++) {if (*i==ht.s) isin=true;}
}
if (!isin && !shift)
{ sellimbs.clear(); selshapes.clear();
if (ht.n>=0) {sellimbs.push_back(ht.n); int si=circleshape_from_limb(ht.n); if (si!=-1) selshapes.push_back(si);}
else {selshapes.push_back(ht.s); int li=circlelimb_from_shape(ht.s); if (li!=-1) sellimbs.push_back(li);}
hit=ht; mode=mNothing; Redraw();
}
else if (!isin && shift)
{ if (ht.n>=0) {sellimbs.push_back(ht.n); int si=circleshape_from_limb(ht.n); if (si!=-1) selshapes.push_back(si);}
else {selshapes.push_back(ht.s); int li=circlelimb_from_shape(ht.s); if (li!=-1) sellimbs.push_back(li);}
hit=ht; mode=mNothing; Redraw();
}
bool keybline=true;
if (ht.n==-1 && ht.s!=-1 && ht.type==htShape) keybline=false;
// We will do a general sort of right-click menu here, which works for
// both shapes and limbs, an arbitrary number of them. Some options aren't
// available in all cases.
// line/arc/spring/circle - only if sellimb=1
// --
// Copy }
// Cut } only if sellimbs>1
// Paste } additionally, paste requires that sellimb=1, and is grey otherwise
// -- }
// Insert Line }
// Delete Line } only if 1 limb selected
// -- }
// Flip }
// Enlarge } only if 1 or more limbs selected
// Shrink }
// -- }
// Frequency -> (list) -- present if 1 or more limbs selected
// Line -> invisible/thickness/(list) -- always there, refers to lines and shape outlines
// Fill -> invisible/anti-overlap/(list)/(blist) -- present if shape>=1||circle>=1, refers to shape fills
// Order -> tofront/toback -- always there, keeps relative order
// Anchor -> toleft/tobottom/toright/totop -- present if 1 or more limbs selected, applies to all of them
enum {rmAnchNone=1, rmAnchLeft=2, rmAnchRight=3, rmAnchTop=4, rmAnchBottom=5,
rmOrderFront=10, rmOrderBack=11,
rmFillVisible=12, rmFillInvisible=13, rmFillAlternate=14, rmFillWinding=15, rmFillMore=16, rmFill=17, rmFillLast=49,
rmLineVisible=50, rmLineInvisible=51, rmLineMore=52, rmLineExtra2=53, rmLineExtra1=54, rmLineThick=55, rmLineMedium=56, rmLineThin=57, rmLine=58, rmLineLast=99,
rmFreqFixed=111, rmFreqNegative=113, rmFreqLeft=114, rmFreqRight=125, rmFreqDifference=135, rmFreqKaraoke=143,
rmShrink=151, rmEnlarge=152, rmFlip=153, rmInsert=154, rmDelete=155,
rmPaste=156, rmCut=157, rmCopy=158, rmType=159,
rmMoreBitmaps=180, rmBitmaps=181, rmBitmapsLast=250,
rmMoreStyles=251,
rmLineStyleFirst=252,rmLineStyleLast=352,
rmFreqStyleFirst=353,rmFreqStyleLast=453,
rmFillStyleFirst=454,rmFillStyleLast=555,
rmEffectsMore=556, rmLineEffectsFirst=557, rmLineEffectsLast=600, rmFillEffectsFirst=601, rmFillEffectsLast=699,
rmFreqCumMore=700, rmFreqCumFirst=701, rmFreqCumLast=799};
HMENU hrightmenu=CreatePopupMenu(), hordmenu=CreatePopupMenu(), hanchmenu=CreatePopupMenu();
HMENU hlinemenu=CreatePopupMenu(), hfillmenu=CreatePopupMenu(), hfreqmenu=CreatePopupMenu();
vector<COLORREF> extracols;
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
//
// Anchor -> toleft/tobottom/toright/totop -- present if 1 or more limbs selected, applies to all of them
if (sellimbs.size()>0)
{ int ia=-2;
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ int a=body->limbs[*i].anchor;
if (ia==-2) ia=a; else if (ia!=a) ia=-1;
}
im(hanchmenu,"To left",rmAnchLeft,ia==4);
im(hanchmenu,"To bottom",rmAnchBottom,ia==3);
im(hanchmenu,"To right",rmAnchRight,ia==2);
im(hanchmenu,"To top",rmAnchTop,ia==1);
im(hanchmenu,"None",rmAnchNone,ia==0);
im(hrightmenu,"Anchor",hanchmenu);
}
//
// Order -> tofront/toback -- always there, keeps relative order
im(hordmenu,"To back\tEnd",rmOrderBack);
im(hordmenu,"To front\tHome",rmOrderFront);
im(hrightmenu,"Order",hordmenu);
//
// Fill -> none/(list) -- present if shape>=1||circles>=1, refers to shape fills
bool fillable = (selshapes.size()>0);
if (!fillable)
{ for (list<int>::const_iterator sli=sellimbs.begin(); sli!=sellimbs.end() && !fillable; sli++)
{ if (body->limbs[*sli].type==3) fillable=true;
}
}
if (fillable)
{ list<COLORREF> cols; bool somenotrgb=false;
list<string> effects; bool somenoteffects=false;
list<string> bitmaps; bool somenotbitmaps=false;
bool allinvisible=true, allalternate=true; string allfillstyle="==";
//
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
string thisstyle=shape.fillstyle;
if (allfillstyle=="==") allfillstyle=thisstyle;
else if (allfillstyle!=thisstyle) allfillstyle="=";
//
if (!shape.balternate) allalternate=false;
//
if (shape.brush.type!=ctNone) allinvisible=false;
if (shape.brush.type==ctBitmap) bitmaps.push_back(shape.brush.bitmap);
else somenotbitmaps=true;
if (shape.brush.type == ctRGB) cols.push_back(RGB(shape.brush.rgb.r, shape.brush.rgb.g, shape.brush.rgb.b));
else somenotrgb=true;
if (shape.brush.type==ctEffect) effects.push_back(shape.brush.effect);
else somenoteffects=true;
}
cols.sort(); cols.unique(); bitmaps.sort(); bitmaps.unique(); effects.sort(); effects.unique();
//
im(hfillmenu,"Styles...",rmMoreStyles);
im(hfillmenu,body,rmFillStyleFirst,ht.n==-1 && !keybline,allfillstyle);
im(hfillmenu,"--");
im(hfillmenu,"Effects...",rmEffectsMore);
im(hfillmenu,body->effects,effects,somenoteffects,rmFillEffectsFirst);
im(hfillmenu,"--");
string bitmapsel="-"; if (bitmaps.size()==1 && !somenotbitmaps) bitmapsel=bitmaps.front();
im(hfillmenu,"Bitmaps...",rmMoreBitmaps);
for (int bic=0; bic<(int)body->bmps.size(); bic++)
{ string bname = body->bmps[bic].name;
bool checked = (StringLower(bname)==StringLower(bitmapsel));
im(hfillmenu,bname,rmBitmaps+bic,checked,true,true);
}
im(hfillmenu,"--");
im(hfillmenu,"Colours...",rmFillMore);
im(hfillmenu,cols,somenotrgb,rmFill,!keybline,&extracols);
im(hfillmenu,"--");
im(hfillmenu,"Self-inverse",allalternate?rmFillWinding:rmFillAlternate,allalternate,true,false);
string s="Invisible"; if (!keybline) s+="\tV";
im(hfillmenu,s,allinvisible?rmFillVisible:rmFillInvisible,allinvisible,true,false);
im(hrightmenu,"Fill",hfillmenu);
}
// Line -> invisible/thickness/(list) -- always there, refers to lines and shape outlines
list<COLORREF> cols; bool notallrgb=false;
list<string> lineeffects; bool notalleffects=false;
bool allinvisible=true; int thick=-2;
string alllinestyle("==");
for (list<int>::const_iterator sli=sellimbs.begin(); sli!=sellimbs.end(); sli++)
{ TLimb &limb = body->limbs[*sli];
bool is_a_shaped_circle = (limb.type==3 && circleshape_from_limb(*sli)!=-1);
// we ignore a limb-circle if it has a shape, for populating the line menu
if (!is_a_shaped_circle)
{ if (limb.color.type == ctRGB) { cols.push_back(RGB(limb.color.rgb.r, limb.color.rgb.g, limb.color.rgb.b)); allinvisible = false; }
else notallrgb=true;
if (limb.color.type==ctEffect) {lineeffects.push_back(limb.color.effect); allinvisible=false;}
else notalleffects=false;
//
int it=0; if (limb.thickness<0.5) it=0; else if (limb.thickness<1.5) it=1;
else if (limb.thickness<3) it=2; else if (limb.thickness<6) it=3; else it=4;
if (limb.color.type==ctNone) thick=-1;
if (thick==-2) thick=it; else if (thick!=it) thick=-1;
//
string thisstyle=limb.linestyle;
if (alllinestyle=="==") alllinestyle=thisstyle;
else if (alllinestyle!=thisstyle) alllinestyle="=";
}
}
for (list<int>::const_iterator ssi=selshapes.begin(); ssi!=selshapes.end(); ssi++)
{ stk::TShape &shape = body->shapes[*ssi];
if (shape.line.type==ctRGB) {cols.push_back(CREF(shape.line.rgb)); allinvisible=false;}
else notallrgb=true;
if (shape.line.type==ctEffect) {lineeffects.push_back(shape.line.effect); allinvisible=false;}
else notalleffects=true;
if (shape.line.type!=ctNone && shape.line.type!=ctRGB && shape.line.type!=ctEffect) LUASSERTMM("unknown shape color");
//
int it=0; if (shape.thickness<0.5) it=0; else if (shape.thickness<1.5) it=1; else it=2;
if (shape.line.type==ctNone) thick=-1;
if (thick==-2) thick=it; else if (thick!=it) thick=-1;
//
string thisstyle=shape.linestyle;
if (alllinestyle=="==") alllinestyle=thisstyle;
else if (alllinestyle!=thisstyle) alllinestyle="=";
}
cols.sort(); cols.unique();
lineeffects.sort(); lineeffects.unique();
//
im(hlinemenu,"Styles...",rmMoreStyles);
im(hlinemenu,body,rmLineStyleFirst,ht.n!=-1 || keybline,alllinestyle);
im(hlinemenu,"--");
im(hlinemenu,"Effects...",rmEffectsMore);
im(hlinemenu,body->effects,lineeffects,notalleffects,rmLineEffectsFirst,imDisallowBitmaps);
im(hlinemenu,"--");
im(hlinemenu,"Colours...",rmLineMore);
im(hlinemenu,cols,notallrgb,rmLine,keybline,&extracols);
im(hlinemenu,"--");
im(hlinemenu,"Extra2",rmLineExtra2,thick==4);
im(hlinemenu,"Extra1",rmLineExtra1,thick==3);
im(hlinemenu,"Heavy\tH",rmLineThick,thick==2);
im(hlinemenu,"Medium\tM",rmLineMedium,thick==1);
im(hlinemenu,"Thin\tT",rmLineThin,thick==0);
im(hlinemenu,"--");
string s="Invisible"; if (keybline) s+="\tV";
im(hlinemenu,s,allinvisible?rmLineVisible:rmLineInvisible,allinvisible,true,false);
im(hrightmenu,"Line",hlinemenu);
//
// Frequency -> (list) -- present if 1 or more limbs selected
vector<CumInfo> retcums; // this will be constructed by the cumulative menu
if (sellimbs.size()>0)
{ int chan=-2, band=-2, neg=-2; //-2=unassinged, -1=contradiction, 0+=value
list<CumInfo> cums; // lists all the cums that we've seen so far
bool anynonfixed=false; // for whether any have a chan=0,1,2 (and so can be negated and cum'd)
string allfreqstyle("==");
for (list<int>::const_iterator sli=sellimbs.begin(); sli!=sellimbs.end(); sli++)
{ TLimb &limb = body->limbs[*sli];
int c=limb.chan, b=limb.band; int n=0; if (limb.negative&&c!=4) n=1;
if (chan==-2) chan=c; else if (chan!=c) chan=-1;
if (band==-2) band=b; else if (band!=b) band=-1;
if (limb.chan<=3)
{ anynonfixed=true;
if (neg==-2) neg=n; else if (neg!=n) neg=-1;
if (limb.cum) cums.push_back(CumInfo(limb.crate,limb.creflect)); else cums.push_back(CumInfo(0,0));
}
//
string thisstyle=limb.freqstyle;
if (allfreqstyle=="==") allfreqstyle=thisstyle;
else if (allfreqstyle!=thisstyle) allfreqstyle="=";
}
cums.sort(); cums.unique();
//
im(hfreqmenu,"Styles...",rmMoreStyles);
im(hfreqmenu,body,rmFreqStyleFirst,false,allfreqstyle);
if (anynonfixed)
{ im(hfreqmenu,"--");
im(hfreqmenu,"Cumulatives...",rmFreqCumMore);
im(hfreqmenu,cums,rmFreqCumFirst,retcums);
im(hfreqmenu,"Negative",rmFreqNegative,neg==1,true,false);
}
im(hfreqmenu,"--");
im(hfreqmenu,"Music", rmFreqKaraoke+1, chan==3&&band==1);
im(hfreqmenu,"Vocals",rmFreqKaraoke+0, chan==3&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Difference: 6",rmFreqDifference+5, chan==2&&band==5);
im(hfreqmenu,"Difference: 5",rmFreqDifference+4, chan==2&&band==4);
im(hfreqmenu,"Difference: 4",rmFreqDifference+3, chan==2&&band==3);
im(hfreqmenu,"Difference: 3",rmFreqDifference+2, chan==2&&band==2);
im(hfreqmenu,"Difference: 2",rmFreqDifference+1, chan==2&&band==1);
im(hfreqmenu,"Difference: 1",rmFreqDifference+0, chan==2&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Right: 6 treble",rmFreqRight+5, chan==1&&band==5);
im(hfreqmenu,"Right: 5",rmFreqRight+4, chan==1&&band==4);
im(hfreqmenu,"Right: 4",rmFreqRight+3, chan==1&&band==3);
im(hfreqmenu,"Right: 3",rmFreqRight+2, chan==1&&band==2);
im(hfreqmenu,"Right: 2",rmFreqRight+1, chan==1&&band==1);
im(hfreqmenu,"Right: 1 bass\tR",rmFreqRight+0, chan==1&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Left: 6 treble",rmFreqLeft+5, chan==0&&band==5);
im(hfreqmenu,"Left: 5",rmFreqLeft+4, chan==0&&band==4);
im(hfreqmenu,"Left: 4",rmFreqLeft+3, chan==0&&band==3);
im(hfreqmenu,"Left: 3",rmFreqLeft+2, chan==0&&band==2);
im(hfreqmenu,"Left: 2",rmFreqLeft+1, chan==0&&band==1);
im(hfreqmenu,"Left: 1 bass\tL",rmFreqLeft+0, chan==0&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Fixed\tF",rmFreqFixed, chan==4&&band==0);
im(hrightmenu,"Frequency",hfreqmenu);
}
// Flip }
// Enlarge } only if 1 or more limbs selected
// Shrink }
// -- }
if (sellimbs.size()>0)
{ im(hrightmenu,"--");
im(hrightmenu,"Flip",rmFlip);
im(hrightmenu,"Enlarge",rmEnlarge);
im(hrightmenu,"Shrink",rmShrink);
}
// Insert Line }
// Delete Line } only if 1 limb selected
// -- }
if (sellimbs.size()==1)
{ im(hrightmenu,"--");
im(hrightmenu,"Delete Line",rmDelete);
im(hrightmenu,"Insert Line",rmInsert);
}
// Copy }
// Cut } only if sellimbs>1
// Paste } additionally, paste requires that sellimb=1, and is grey otherwise
// -- }
bool cancopy = GetRootLimbsOfSelection(NULL);
if (cancopy)
{ im(hrightmenu,"--");
im(hrightmenu,"Paste",rmPaste,false,sellimbs.size()==1);
im(hrightmenu,"Cut",rmCut);
im(hrightmenu,"Copy",rmCopy);
}
// line/arc/spring/circle - only if sellimb=1
// --
if (sellimbs.size()==1)
{ im(hrightmenu,"--");
TLimb &limb = body->limbs[sellimbs.front()];
if (limb.type==0) im(hrightmenu,"Arc\tA",rmType);
else if (limb.type==1) im(hrightmenu,"Spring\tA",rmType);
else if (limb.type==2) im(hrightmenu,"Circle\tA",rmType);
else im(hrightmenu,"Line\tA",rmType);
}
BalanceMenu(hrightmenu); BalanceMenu(hfreqmenu);
BalanceMenu(hlinemenu); BalanceMenu(hfillmenu);
POINT pt; pt.x=mx; pt.y=my; ClientToScreen(chwnd,&pt);
int cmd=TrackPopupMenu(hrightmenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,chwnd,NULL);
DestroyMenu(hrightmenu);
DestroyMenu(hanchmenu);
DestroyMenu(hfreqmenu);
DestroyMenu(hlinemenu);
DestroyMenu(hfillmenu);
DestroyMenu(hordmenu);
mode=mNothing;
if (cmd==0) return;
//
if (cmd==rmLineVisible) SetVisibility(tsLine,1);
else if (cmd==rmLineInvisible) SetVisibility(tsLine,0);
else if (cmd==rmFillVisible) {LazyCreateCircleShapes(); SetVisibility(tsFill,1);}
else if (cmd==rmFillInvisible) SetVisibility(tsFill,0);
else if (cmd==rmFillAlternate) SetAlternate(1);
else if (cmd==rmFillWinding) SetAlternate(0);
else if (cmd==rmType) ToggleLineType();
else if (cmd==rmDelete) DeleteLimbOrShape();
else if (cmd==rmInsert) InsertLimb();
else if (cmd==rmCopy) Copy();
else if (cmd==rmCut) Cut();
else if (cmd==rmPaste) Paste();
else if (cmd==rmEnlarge) Stretch(1);
else if (cmd==rmShrink) Stretch(-1);
else if (cmd==rmFillMore||cmd==rmLineMore) UserColours(mhwnd);
else if (cmd==rmMoreBitmaps) Bitmaps(mhwnd);
else if (cmd>=rmBitmaps && cmd<=rmBitmapsLast) {LazyCreateCircleShapes(); SetBitmap(body->bmps[cmd-rmBitmaps].name);}
else if (cmd==rmFlip) Flip();
else if (cmd==rmOrderFront) SetOrder(2);
else if (cmd==rmOrderBack) SetOrder(-2);
else if (cmd==rmFreqNegative) ToggleNegative();
else if (cmd>=rmFreqDifference && cmd<=rmFreqDifference+5) SetChanBand(2,cmd-rmFreqDifference);
else if (cmd>=rmFreqLeft && cmd<=rmFreqLeft+5) SetChanBand(0,cmd-rmFreqLeft);
else if (cmd>=rmFreqRight && cmd<=rmFreqRight+5) SetChanBand(1,cmd-rmFreqRight);
else if (cmd>=rmFreqKaraoke && cmd<=rmFreqKaraoke+5) SetChanBand(3,cmd-rmFreqKaraoke);
else if (cmd==rmFreqFixed) SetChanBand(4,0);
else if (cmd>=rmFreqCumFirst && cmd<=rmFreqCumLast) SetCum(retcums[cmd-rmFreqCumFirst].d,retcums[cmd-rmFreqCumFirst].r);
else if (cmd==rmFreqCumMore) UserCumulatives(mhwnd);
else if (cmd==rmAnchNone) SetAnchor(0);
else if (cmd==rmAnchLeft) SetAnchor(4);
else if (cmd==rmAnchRight) SetAnchor(2);
else if (cmd==rmAnchBottom) SetAnchor(3);
else if (cmd==rmAnchTop) SetAnchor(1);
else if (cmd==rmLineExtra2) SetThickness(8.0);
else if (cmd==rmLineExtra1) SetThickness(4.0);
else if (cmd==rmLineThick) SetThickness(2.0);
else if (cmd==rmLineMedium) SetThickness(1.0);
else if (cmd==rmLineThin) SetThickness(0.0);
else if ((cmd>=rmLine && cmd<=rmLineLast) || (cmd>=rmFill && cmd<=rmFillLast))
{ TSetSubject subj=tsLine; int c=cmd-rmLine;
if (cmd>=rmFill && cmd<=rmFillLast) {subj=tsFill; c=cmd-rmFill;}
if (subj==tsFill) LazyCreateCircleShapes();
if (c<ncols+(int)usercols.size()) SetCol(subj,(TColIndex)c);
else
{ int e=c-ncols-(int)usercols.size(); COLORREF r=extracols[e];
SetCol(subj,GetRValue(r),GetGValue(r),GetBValue(r));
}
}
else if (cmd>=rmLineEffectsFirst && cmd<=rmLineEffectsLast) SetEffect(tsLine,body->effects[cmd-rmLineEffectsFirst].name);
else if (cmd>=rmFillEffectsFirst && cmd<=rmFillEffectsLast)
{ bool anybitmaps=false; const TEffect &eff = body->effects[cmd-rmFillEffectsFirst];
for (vector<stk::TColor>::const_iterator i=eff.cols.begin(); i!=eff.cols.end(); i++)
{ if (i->type==ctBitmap) {anybitmaps=true; break;}
}
if (anybitmaps) LazyCreateCircleShapes();
SetEffect(tsFill,body->effects[cmd-rmFillEffectsFirst].name);
}
else if (cmd==rmEffectsMore) Effects(mhwnd);
else if (cmd==rmMoreStyles) Styles(mhwnd);
else if (cmd>=rmLineStyleFirst && cmd<=rmLineStyleLast) SetStyle(tsLine,cmd-rmLineStyleFirst);
else if (cmd>=rmFillStyleFirst && cmd<=rmFillStyleLast) {LazyCreateCircleShapes(); SetStyle(tsFill,cmd-rmFillStyleFirst);}
else if (cmd>=rmFreqStyleFirst && cmd<=rmFreqStyleLast)
{ SetStyle(tsFreq,cmd-rmFreqStyleFirst);
}
}
void TEditor::LazyCreateCircleShapes()
{ // This is because we display a fill menu for any circle limbs that
// are selected -- even if they don't yet have a shape.
// This function is called when a fill operation is applied.
// We have to create any needed shapes, and add them to the selection.
for (list<int>::const_iterator sli=sellimbs.begin(); sli!=sellimbs.end(); sli++)
{ TLimb &limb = body->limbs[*sli];
bool iscircle = (limb.type==3);
if (!iscircle) continue;
int si = circleshape_from_limb(*sli);
if (si!=-1) continue; // i.e. if it already had a circle shape, we're okay
stk::TShape s; s.limbs=false; s.balternate=false;
s.brush.type=ctRGB; s.brush.dtype=ctRGB; s.brush.rgb=RGBCOLOR(defcols[cYellow].r,defcols[cYellow].g,defcols[cYellow].b);
s.line=limb.color; s.thickness=limb.thickness; limb.color.type=ctNone;
TJointRef j; j.i=*sli; j.ar=true; s.p.push_back(j); j.ar=false; s.p.push_back(j);
si=(int)body->shapes.size();
body->shapes.push_back(s);
selshapes.push_back(si);
}
}
void TEditor::ToggleLineType()
{ if (sellimbs.size()==0) return;
MarkUndo();
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb=body->limbs[*i];
bool wasspring = (limb.type==2||limb.type==3);
limb.type = (limb.type+1)%4;
bool isspring = (limb.type==2||limb.type==3);
if (wasspring && !isspring)
{ // adjust ascale/f to match aspring.
if (limb.chan==4 && limb.band==0)
{ limb.aspring=limb.f;
}
else
{ if (limb.ascale>0)
{ while (limb.aspring<0) limb.aspring+=2*pi; while (limb.aspring>2*pi) limb.aspring-=2*pi;
if (limb.aspring>limb.ascale) {limb.ascale=limb.aspring*1.3; if (limb.ascale>2*pi) limb.ascale=2*pi;}
limb.f=limb.aspring/limb.ascale;
}
else
{ while (limb.aspring<-2*pi) limb.aspring+=2*pi; while (limb.aspring>0) limb.aspring-=2*pi;
if (limb.aspring<limb.ascale) {limb.ascale=limb.aspring*1.3; if (limb.ascale<-2*pi) limb.ascale=-2*pi;}
limb.f=limb.aspring/limb.ascale;
}
}
}
else if (!wasspring && isspring)
{ // adjust aspring to match ascale/f
if (limb.chan==4 && limb.band==0) limb.aspring=limb.f;
else limb.aspring = limb.f*limb.ascale;
// length is by definition fine: because an angled line has 'length',
// and a spring goes in the range 'lmin->length'. So we just need to fix up lmin
if (limb.lmin>limb.length) limb.lmin=limb.length*0.5;
}
}
if (sellimbs.size()==1) Recalc(sellimbs.front());
else Recalc(0);
ismodified=true;
Redraw(); SetCursor();
}
void TEditor::ToggleNegative()
{ nextfreqstyle="";
if (sellimbs.size()==0) return;
MarkUndo();
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (limb.chan!=4) limb.negative=!limb.negative;
// (can't have negative on a fixed limb)
limb.freqstyle="";
}
ismodified=true;
Redraw(); SetCursor();
}
void TEditor::SetAlternate(int newa)
{ if (selshapes.size()==0) return;
MarkUndo();
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
if (newa==0) shape.balternate=false;
else if (newa==1) shape.balternate=true;
else shape.balternate = !shape.balternate;
}
ismodified=true;
Redraw();
}
void TEditor::SetVisibility(TSetSubject subj,int newv)
{ if (subj==tsWhatever)
{ // tsWhatever means that it will be line or fill, according to which one
// the user clicked on most recently to select.
subj=tsLine;
if (hit.n==-1 && hit.s!=-1 && hit.type==htShape) subj=tsFill;
}
if (subj==tsLineFill || subj==tsFill) nextfillstyle="";
if (subj==tsLine || subj==tsLineFill) nextlinestyle="";
if (sellimbs.size()==0 && selshapes.size()==0) return;
MarkUndo();
//
if (subj==tsLine || subj==tsLineFill)
{ for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (circleshape_from_limb(*i)==-1)
{ if (newv==0) {if (limb.color.type!=ctNone) limb.color.otype=limb.color.type; limb.color.type=ctNone;}
else if (newv==1) limb.color.type=limb.color.otype;
else {if (limb.color.type==ctNone) limb.color.type=limb.color.otype; else {limb.color.otype=limb.color.type; limb.color.type=ctNone;}}
limb.linestyle="";
}
else {limb.linestyle=""; limb.color.type=ctNone;}
}
}
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
if (subj==tsLine || subj==tsLineFill)
{ if (newv==0) {if (shape.line.type!=ctNone) shape.line.otype=shape.line.type; shape.line.type=ctNone;}
else if (newv==1) shape.line.type=shape.line.otype;
else {if (shape.line.type==ctNone) shape.line.type=shape.line.otype; else {shape.line.otype=shape.line.type; shape.line.type=ctNone;}}
shape.linestyle="";
}
if (subj==tsFill || subj==tsLineFill)
{ if (newv==0) {if (shape.brush.type!=ctNone) shape.brush.otype=shape.brush.type; shape.brush.type=ctNone;}
else if (newv==1) shape.brush.type=shape.brush.otype;
else {if (shape.brush.type==ctNone) shape.brush.type=shape.brush.otype; else {shape.brush.otype=shape.brush.type; shape.brush.type=ctNone;}}
shape.fillstyle="";
}
}
MakeBindexes(body); MakeEindexes(body); body->RecalcEffects(true);
ismodified=true;
Redraw(); SetCursor();
}
void TEditor::SetAnchor(int anch)
{ if (sellimbs.size()==0) return;
MarkUndo();
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
limb.anchor = anch;
}
ismodified=true;
Redraw(); SetCursor();
}
void TEditor::SetCum(double c,int reflect)
{ if (sellimbs.size()==0) return;
MarkUndo();
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (!(limb.chan<=3)) continue;
if (c==0) limb.cum=false;
else {limb.cum=true; limb.crate=c; limb.creflect=reflect;}
limb.freqstyle="";
}
ismodified=true;
}
void TEditor::SetChanBand(int ac,int ab)
{ nextchan=ac; nextband=ab; IncNextChan(); nextfreqstyle="";
if (sellimbs.size()==0) return;
MarkUndo();
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb=body->limbs[*i];
int c=ac,b=ab;
if (b==-1) b=limb.band;
if (c==-1) c=limb.chan;
limb.band=b;
limb.chan=c;
RepositioningMove(*i,b2x(limb.x),b2y(limb.y),true);
limb.freqstyle="";
}
ismodified=true;
Recalc(0);
Redraw(); SetCursor();
}
void TEditor::SetStyle(char shortcutkey)
{ int i=0;
for (list<TStyle>::const_iterator si=body->styles.begin(); si!=body->styles.end(); si++,i++)
{ if (si->shortcut==shortcutkey) {SetStyle(tsWhatever,i); return;}
}
return;
}
void TEditor::SetStyle(TSetSubject subj, int index)
{ list<TStyle>::const_iterator si=body->styles.begin();
for (int i=0; i<index; i++) si++;
const TStyle &style = *si;
if (subj==tsWhatever)
{ subj=tsLine;
if (hit.n==-1 && hit.s!=-1 && hit.type==htShape) subj=tsFill;
if (hit.n==-1 && hit.s==-1) {nextfreqstyle=style.name; nextlinestyle=style.name; nextfillstyle=style.name;}
else if (hit.n!=-1) {nextfreqstyle=style.name; nextlinestyle=style.name;}
else {nextfillstyle=style.name;}
}
else if (subj==tsFreq) nextfreqstyle=style.name;
else if (subj==tsLine) nextlinestyle=style.name;
else if (subj==tsFill) nextfillstyle=style.name;
MarkUndo();
bool anybmps=false;
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (subj==tsFreq)
{ limb.freqstyle=style.name;
limb.chan=style.limb.chan; limb.band=style.limb.band; limb.negative=style.limb.negative;
limb.cum=style.limb.cum; limb.crate=style.limb.crate; limb.creflect=style.limb.creflect;
RepositioningMove(*i,b2x(limb.x),b2y(limb.y),true);
}
if (subj==tsLine && circleshape_from_limb(*i)==-1)
{ limb.linestyle=style.name;
limb.color=style.limb.color;
limb.thickness=style.limb.thickness;
}
}
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
if (subj==tsFill)
{ shape.fillstyle=style.name;
shape.brush=style.shape.brush;
anybmps=true;
}
if (subj==tsLine)
{ shape.linestyle=style.name;
shape.line=style.limb.color;
shape.thickness=style.limb.thickness;
}
}
ismodified=true;
if (anybmps) MakeBindexes(body);
MakeEindexes(body); Recalc(0);
Redraw(); SetCursor();
}
void TEditor::SetCol(TSetSubject subj, TColIndex i)
{ if (i<ncols) SetCol(subj,defcols[i].r,defcols[i].g,defcols[i].b);
else
{ int ci=ncols; list<TUserColour>::const_iterator ui=usercols.begin();
while (ci<i) {ci++; ui++;}
SetCol(subj,ui->c.r,ui->c.g,ui->c.b);
}
}
void TEditor::SetCol(TSetSubject subj,int r,int g,int b)
{ if (subj==tsWhatever)
{ subj=tsLine;
if (hit.n==-1 && hit.s!=-1 && hit.type==htShape) subj=tsFill;
}
if (subj==tsLine || subj==tsLineFill || subj==tsFill) nextlinestyle="";
if (subj==tsLineFill || subj==tsFill) nextfillstyle="";
if (sellimbs.size()==0 && selshapes.size()==0) return;
MarkUndo();
//
if (subj==tsLine || subj==tsLineFill)
{ for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (circleshape_from_limb(*i)==-1)
{ limb.color.type=ctRGB; limb.color.dtype=ctRGB; limb.color.rgb=RGBCOLOR(r,g,b);
limb.linestyle="";
}
}
}
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
if (subj==tsLine || subj==tsLineFill)
{ shape.line.type=ctRGB; shape.line.dtype=ctRGB; shape.line.rgb=RGBCOLOR(r,g,b);
shape.linestyle="";
}
if (subj==tsFill || subj==tsLineFill)
{ shape.brush.type=ctRGB; shape.brush.dtype=ctRGB; shape.brush.rgb=RGBCOLOR(r,g,b);
shape.brush.bindex=-1;
shape.fillstyle="";
}
}
ismodified=true; body->RecalcEffects(true);
Redraw(); SetCursor();
}
void TEditor::SetEffect(TSetSubject subj,const string effect)
{ if (subj==tsWhatever)
{ subj=tsLine;
if (hit.n==-1 && hit.s!=-1 && hit.type==htShape) subj=tsFill;
}
if (subj==tsLine || subj==tsLineFill || subj==tsFill) nextlinestyle="";
if (subj==tsLineFill || subj==tsFill) nextfillstyle="";
if (sellimbs.size()==0 && selshapes.size()==0) return;
MarkUndo();
//
if (subj==tsLine || subj==tsLineFill)
{ for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (circleshape_from_limb(*i)==-1)
{ limb.color.type=ctEffect; limb.color.effect=effect;
limb.linestyle="";
}
}
}
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
if (subj==tsLine || subj==tsLineFill)
{ shape.line.type=ctEffect; shape.line.effect=effect;
shape.linestyle="";
}
if (subj==tsFill || subj==tsLineFill)
{ shape.brush.type=ctEffect; shape.brush.effect=effect;
shape.fillstyle="";
}
}
ismodified=true;
MakeEindexes(body); body->RecalcEffects(true);
Redraw(); SetCursor();
}
void TEditor::SetBitmap(const string bn)
{ nextfillstyle="";
if (selshapes.size()==0) return;
MarkUndo();
int bindex=body->bindex(bn); LUASSERT(bindex!=-1);
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
// we'll only set the bitmap if it's a circle-fill
int li = circlelimb_from_shape(*i);
if (li!=-1)
{ shape.brush.type=ctBitmap; shape.brush.dtype=ctBitmap;
shape.brush.bitmap = bn;
shape.brush.bindex = bindex;
shape.fillstyle="";
TLimb &limb = body->limbs[li];
limb.color.type=ctNone; limb.color.dtype=ctNone;
}
}
ismodified=true;
if (WhitePrint) {WhitePrint=false;UpdateMenus();}
Redraw(); SetCursor();
}
void TEditor::SetThickness(double t)
{ nextlinestyle="";
if (sellimbs.size()==0 && selshapes.size()==0) return;
MarkUndo();
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (circleshape_from_limb(*i)==-1)
{ limb.thickness=t;
if (limb.color.type==ctNone) limb.color.type=limb.color.otype;
limb.linestyle="";
}
}
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++)
{ stk::TShape &shape = body->shapes[*i];
shape.thickness = t;
if (shape.line.type==ctNone) {shape.line.type=ctRGB; shape.line.dtype=ctRGB;}
shape.linestyle="";
}
ismodified=true;
Redraw(); SetCursor();
}
void TEditor::SetOrder(int dir)
{ if (dir!=2 && dir!=-2 && dir!=1 && dir!=-1) return;
if (sellimbs.size()==0 && selshapes.size()==0) return;
MarkUndo();
vector<bool> sbitmap; sbitmap.resize(body->shapes.size());
for (list<int>::const_iterator i=selshapes.begin(); i!=selshapes.end(); i++) sbitmap[*i]=true;
bool anyreallimbsselected=false;
// if a circleshape+circlelimb is selected, that's not enough to count for
// lines to have their order changed.
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb = body->limbs[*i];
if (limb.type!=3) anyreallimbsselected=true;
else
{ int si = circleshape_from_limb(*i);
if (si==-1) anyreallimbsselected=true;
}
}
if (anyreallimbsselected)
{ for (int i=0; i<(int)body->shapes.size(); i++) {if (body->shapes[i].limbs) sbitmap[i]=true;}
}
// now 'sbitmaps' indicates whose order we want to change
// we will construct a new shape-vector 'nss' with the new order
vector<stk::TShape> nss;
int numsel=0;
// those of them moved to the front...
if (dir==-2)
{ for (int i=0; i<(int)sbitmap.size(); i++)
{ if (sbitmap[i]) {numsel++; nss.push_back(body->shapes[i]);}
}
}
// those of them left in the middle
for (int i=0; i<(int)sbitmap.size(); i++)
{ if (!sbitmap[i]) nss.push_back(body->shapes[i]);
}
// those of them moved to the end...
if (dir==2)
{ for (int i=0; i<(int)sbitmap.size(); i++)
{ if (sbitmap[i]) {numsel++; nss.push_back(body->shapes[i]);}
}
}
body->shapes=nss;
//
// now let's select our changes
selshapes.clear();
if (dir==-2) {for (int i=0; i<numsel; i++) {if (!body->shapes[i].limbs) selshapes.push_back(i);}}
else {for (int i=(int)body->shapes.size()-numsel; i<(int)body->shapes.size(); i++) {if (!body->shapes[i].limbs) selshapes.push_back(i);}}
ismodified=true;
Redraw(); SetCursor();
}
void TEditor::ButtonDown(int mx,int my)
{ if (tool==tZoom) {zoomx0=mx; zoomy0=my; zoomx=mx; zoomy=my; mode=mZoomDragging; return;}
//
THitTest t=PointAtCoords(mx,my,false);
int shift = GetAsyncKeyState(VK_SHIFT)<0;
if (!shift) {sellimbs.clear(); selshapes.clear();}
//
int oldhit = hit.n;
hit.s=-1; hit.n=-1; hit.type=htMiss; hit.sf=0; hit.si=0; mode=mNothing;
if (t.s==-1 && t.n==-1)
{ zoomx0=mx; zoomy0=my; zoomx=mx; zoomy=my; mode=mSelDragging; return;
}
// Otherwise, it was a click on something, and how we respond depends in a complicated
// way on our mode and on what it was.
if (t.n!=-1) // was it a click on a limb?
{ list<int>::iterator wassel=sellimbs.begin(); while (wassel!=sellimbs.end() && *wassel!=t.n) wassel++;
list<int>::iterator wasselshape=selshapes.end();
int si=circleshape_from_limb(t.n);
if (si != -1) for (wasselshape = selshapes.begin(); wasselshape != selshapes.end() && *wasselshape != si; wasselshape++) {}
if (shift && (wassel!=sellimbs.end() || wasselshape!=selshapes.end()))
{ if (wassel!=sellimbs.end()) sellimbs.erase(wassel);
if (wasselshape!=selshapes.end()) selshapes.erase(wassel);
Redraw();return;
}
if (oldhit>=0 && t.n==body->limbs[oldhit].root && t.type==htSpot) {hit.n=oldhit; hit.type=htRoot;} // if clicked on the root of something already selected
else {hit.type=t.type; hit.n=t.n;}
hit.s=t.s; sellimbs.push_back(hit.n); sellimbs.sort(); sellimbs.unique();
if (si!=-1) {selshapes.push_back(si); selshapes.sort(); selshapes.unique();}
mode=mNodePressing; UpdateMenus(); Redraw(); return;
}
// otherwise it was a click on a shape
list<int>::iterator wassel=selshapes.begin(); while (wassel!=selshapes.end() && *wassel!=t.s) wassel++;
list<int>::iterator wassellimb=sellimbs.end();
int li=circlelimb_from_shape(t.s);
if (li != -1) for (wassellimb = sellimbs.begin(); wassellimb != sellimbs.end() && *wassellimb != li; wassellimb++) {}
if (shift && (wassel!=selshapes.end() || wassellimb!=sellimbs.end()))
{ if (wassel!=selshapes.end()) selshapes.erase(wassel);
if (wassellimb!=sellimbs.end()) sellimbs.erase(wassellimb);
Redraw();return;
}
if (tool==tCreate && t.type==htLine) mode=mShapeLinePressing;
else if (tool==tCreate && t.type==htSpot) mode=mShapeSpotPressing;
else if (tool==tEdit && t.type==htSpot) mode=mShapeSpotPressing;
hit.n=-1; hit.s=t.s; hit.type=t.type; hit.sf=t.sf; hit.si=t.si;
selshapes.push_back(hit.s); selshapes.sort(); selshapes.unique();
if (li!=-1) {sellimbs.push_back(li); sellimbs.sort(); sellimbs.unique();}
UpdateMenus(); Redraw(); return;
}
void TEditor::SelectShapeLineWobble(int mx,int my)
{ THitTest t = PointAtCoords(mx,my,false);
if (t.s==hit.s && t.si==hit.si && t.sf>=hit.sf-0.5 && t.sf<=hit.sf+0.5) return;
// we will only ever be here because we're in create mode, and dragging a line
mode=mCreateCornerDragging; // but won't MarkUndo until later...
cori=hit.si; cortarget.i=-1;
CornerMove(mx,my);
}
void TEditor::SelectShapeSpotWobble(int mx,int my)
{ THitTest t = PointAtCoords(mx,my,false);
if (t.s==hit.s && t.si==hit.si && t.type==htSpot) return;
MarkUndo();
mode=mCornerMoving;
// we'll delete this point from the list. Note that all shapes implicitly have at least two points
stk::TShape &shape = body->shapes[hit.s];
corotarget = shape.p[hit.si].i; //bool ar=shape.p[hit.si].ar;
vector<TJointRef> nss;
for (int i=0; i<hit.si; i++) nss.push_back(shape.p[i]);
for (int i=hit.si+1; i<(int)shape.p.size(); i++) nss.push_back(shape.p[i]);
shape.p=nss;
cori=hit.si-1; if (cori<0) cori+=(int)shape.p.size();
cortarget.i=-1;
CornerMove(mx,my);
ShowHint("Either pin this corner to a joint, or drop it 'nowhere' to remove it");
}
void TEditor::IncNextChan()
{ if (nextchan==4) return;
if (nextchan==0 || nextchan==1)
{ nextchan++; if (nextchan==2) {nextchan=0; nextband++; if (nextband==6) nextband=0;}
}
}
void TEditor::SelectWobble(int mx,int my)
{ THitTest t=PointAtCoords(mx,my,false);
if (t.n==hit.n || (hit.type==htRoot && t.n==body->limbs[hit.n].root)) return;
// if move mouse far enough, we go into rubbber-banding to create a line
// or just move an existing node
if (hit.type==htRoot) {hit.n=body->limbs[hit.n].root; hit.type=htSpot;}
if (tool==tCreate && (hit.type==htPlus || hit.type==htSpot)) // drag from a spot
{ mode=mCreateDragging;
rubber.type=0; rubber.negative=false;
rubber.root=hit.n;
rubber.aisoff=true; rubber.chan=nextchan; rubber.band=nextband; rubber.anchor=0;
rubber.cum=false; rubber.crate=1.0; rubber.creflect=0;
rubber.aoff=0; if (rubber.root==0) rubber.aoff=-pi/2; rubber.aspring=0;
if (hit.n==0) rubber.aisoff=false;
rubber.ang=0;
rubber.x0=body->limbs[hit.n].x; rubber.y0=body->limbs[hit.n].y;
rubber.ang0=rubber.aoff; if (rubber.aisoff) rubber.ang0 += body->limbs[hit.n].ang;
rubber.color.type=ctRGB; rubber.color.dtype=ctRGB; rubber.color.rgb=RGBCOLOR(255,255,255); rubber.thickness=1;
rubber.freqstyle=nextfreqstyle;
TStyle style = StyleFromName(rubber.freqstyle); if (style.name!="")
{ rubber.chan=style.limb.chan; rubber.band=style.limb.band; rubber.negative=style.limb.negative;
}
rubber.linestyle=nextlinestyle;
style = StyleFromName(rubber.linestyle); if (style.name!="")
{ rubber.color=style.limb.color; rubber.thickness=style.limb.thickness;
}
CreatingMove(mx,my);
IncNextChan();
}
else if (hit.type==htAmin) // drag an aoff handle
{ if (body->limbs[hit.n].type==0 || body->limbs[hit.n].type==1) mode=mAoffDragging;
else if (body->limbs[hit.n].type==2 || body->limbs[hit.n].type==3) mode=mLminDragging;
if (mode==mAoffDragging) {MarkUndo(); AngleMove(mx,my);}
else if (mode==mLminDragging) {MarkUndo(); SpringMove(mx,my);}
}
else if (hit.type==htAmax) // drag an ascale handle
{ if (body->limbs[hit.n].type==0 || body->limbs[hit.n].type==1) mode=mAscaleDragging;
else if (body->limbs[hit.n].type==2 || body->limbs[hit.n].type==3) mode=mLmaxDragging;
if (mode==mAscaleDragging) {MarkUndo(); AngleMove(mx,my);}
else if (mode==mLmaxDragging) {MarkUndo(); SpringMove(mx,my);}
}
else if (hit.type==htLine) // drag a line
{ MarkUndo();
mode=mNodeMoving;
RepositioningMove(hit.n,mx,my);
}
else if (tool==tEdit && (hit.type==htSpot || hit.type==htPlus)) // drag an existing spot
{ MarkUndo();
mode=mNodeMoving;
RepositioningMove(hit.n,mx,my);
}
}
bool TEditor::SnapToGrid(int *px,int *py)
{ if (!UserGrid) return false;
bool shift = (GetAsyncKeyState(VK_SHIFT)<0);
if (shift) return false;
// this code is copied out from the draw method, since both use the grid.
double interval=1.0; int si;
for (;;)
{ si = b2x(interval)-b2x(0); if (si<60) break; interval /= 5;
si = b2x(interval)-b2x(0); if (si<60) break; interval /= 2;
}
if (si<4) return false;
int lx=b2x(-5), ly=b2y(-5);
int x=*px, y=*py;
while (lx<x-4) lx+=si;
while (ly<y-4) ly+=si;
if (lx<=x+4 && ly<=y+4) {*px=lx; *py=ly; return true;}
return false;
}
double TEditor::SnapAngle(double ang,bool clampzero)
{ const double c=0.2;
if (ang<-2*pi) ang=-2*pi;
if (ang>2*pi) ang=2*pi;
bool shiftdown = (GetAsyncKeyState(VK_SHIFT)<0);
if (UserSnap && shiftdown) return ang;
if (!UserSnap && !shiftdown) return ang;
if (clampzero) {if (ang>-c && ang<c) ang=0;}
//
if (ang>pi/6.0-c && ang<pi/6.0+c) ang=pi/6.0;
if (ang>0.5*pi-c && ang<0.5*pi+c) ang=0.5*pi;
if (ang>pi-c && ang<pi+c) ang=pi;
if (ang>1.5*pi-c && ang<1.5*pi+c) ang=1.5*pi;
if (ang>pi*2.0/3.0-c && ang<pi*2.0/3.0+c) ang=pi*2.0/3.0;
if (ang>pi*4.0/3.0-c && ang<pi*4.0/3.0+c) ang=pi*4.0/3.0;
//
if (ang>-pi/6.0-c && ang<-pi/6.0+c) ang=-pi/6.0;
if (ang>-0.5*pi-c && ang<-0.5*pi+c) ang=-0.5*pi;
if (ang>-pi-c && ang<-pi+c) ang=-pi;
if (ang>-1.5*pi-c && ang<-1.5*pi+c) ang=-1.5*pi;
if (ang>-pi*2.0/3.0-c && ang<-pi*2.0/3.0+c) ang=-pi*2.0/3.0;
if (ang>-pi*4.0/3.0-c && ang<-pi*4.0/3.0+c) ang=-pi*4.0/3.0;
return ang;
}
void TEditor::CornerMove(int mx,int my)
{ corx=x2b(mx); cory=y2b(my);
cortarget.i=-1;
// but we will try to snap to the nearest target
int dmin=-1; TJointRef jmin;
for (int i=0; i<body->nlimbs; i++)
{ TLimb &limb = body->limbs[i];
int x=b2x(limb.x), y=b2y(limb.y);
int dx=mx-x, dy=my-y, dd=(dx*dx)+(dy*dy);
if (dmin==-1 || dd<dmin) {dmin=dd; jmin.i=i; jmin.ar=false;}
if (limb.type==1 || limb.type==3)
{ double xx,yy; jointpos(&xx,&yy,limb,true);
x=b2x(xx); y=b2y(yy);
dx=mx-x; dy=my-y; dd=(dx*dx)+(dy*dy);
if (dd<dmin) {dmin=dd; jmin.i=i; jmin.ar=true;}
}
}
if (dmin<13*13) // 13 pixels snap radius
{ cortarget=jmin;
jointpos(&corx,&cory,body->limbs[cortarget.i],cortarget.ar);
}
Redraw();
}
void TEditor::CreatingMove(int mx,int my)
{ THitTest hit = PointAtCoords(mx,my,false);
if (UserGrid) SnapToGrid(&mx,&my);
rubber.x=x2b(mx); rubber.y=y2b(my);
double dx=rubber.x-rubber.x0, dy=rubber.y-rubber.y0;
TAdjAngle a=AngleNearbyFromOff(dx,dy,rubber.ang0,rubber.ang);
rubber.length=a.relrad;
rubber.lmin=rubber.length*0.4;
rubber.ang=a.screenang;
rubber.ascale=(rubber.ang-rubber.ang0)*1.5;
rubber.ascale=SnapAngle(rubber.ascale,false);
rubber.f=(rubber.ang-rubber.ang0)/rubber.ascale;
rubber.color.type=ctRGB; rubber.color.dtype=ctRGB; rubber.color.rgb=RGBCOLOR(255,255,255); rubber.thickness=1;
TStyle style = StyleFromName(rubber.linestyle); if (style.name!="")
{ rubber.color=style.limb.color; rubber.thickness=style.limb.thickness;
}
rubend.i=-1; rubber.type=0;
if (hit.n!=-1 && hit.type==htSpot && hit.n!=rubber.root) {rubend.i=hit.n; rubend.ar=false;}
if (hit.n!=-1 && hit.type==htAroot) {rubend.i=hit.n; rubend.ar=true;} // no worry about rubber.root, since htAroot will be the arc not the root-joint
if (rubend.i!=-1) {rubber.thickness=2; rubber.color.type=ctRGB; rubber.color.dtype=ctRGB; rubber.color.rgb=RGBCOLOR(255,128,0);}
body->RecalcAngles(&rubber);
Redraw();
}
void TEditor::AngleMove(int mx,int my)
{ TLimb &limb=body->limbs[hit.n];
if (mode==mAscaleDragging)
{ TAdjAngle a=AngleNearbyFromOff(mx-b2x(limb.x0),my-b2y(limb.y0), limb.ang0,limb.ang1);
limb.ascale = SnapAngle(a.relang,false);
ShowHint(StringAng(limb.ascale));
}
else if (mode==mAoffDragging)
{ TAdjAngle a=AngleNearbyFromOff(mx-b2x(limb.x0),my-b2y(limb.y0), limb.ang0,limb.aoff);
double ang=limb.aoff+a.relang;
if (ang>100 || ang<-100) ang=0; // !!! somehow it was too big
while (ang>pi) ang-=2*pi; while (ang<-pi) ang+=2*pi;
limb.aoff = SnapAngle(ang,true);
ShowHint(StringAng(limb.aoff));
}
Recalc(hit.n);
Redraw();
}
void TEditor::SpringMove(int mx,int my)
{ TLimb &limb=body->limbs[hit.n];
// given the line (x0,y0)->ang, we find the point on it that's closest to (xm,ym).
double xm=x2b(mx), ym=y2b(my);
double x0=limb.x0, y0=limb.y0;
double len;
if (cos(limb.ang)<0.01 && cos(limb.ang)>-0.01)
{ if (sin(limb.ang)<0) len=(y0-ym);
else len=(ym-y0);
}
else
{ double m = sin(limb.ang) / cos(limb.ang);
double x = (m*ym + xm - m*y0 + m*m*x0) / (m*m+1);
//double y = m*x + y0-m*x0;
len = (x-x0) / cos(limb.ang);
}
if (mode==mLminDragging)
{ if (len>limb.length) len=limb.length;
if (len<0) len=0;
limb.lmin=len;
ShowHint(StringLength(limb.lmin)+", "+StringFrac(limb.lmin/limb.length));
}
else if (mode==mLmaxDragging)
{ if (len<limb.lmin) len=limb.lmin;
limb.length=len;
ShowHint(StringLength(limb.length));
}
Recalc(hit.n);
Redraw();
}
void TEditor::RubberMove(int mx,int my)
{ zoomx=mx; zoomy=my;
Redraw();
}
void TEditor::SetScrollBars()
{ if (!isready) return;
// The client area is width*height. Let's translate this into body coords.
// note: we have "funky edge effect" using width-1 but just height.
// This was needed for some reason, since otherwise the calling Scroll()
// after SetScrollBars() wasn't stable (i.e. each iteration would move the image left).
// I don't understand why - must be something to do with rounding errors or edge effects?
s_bleft=x2b(0); s_bright=x2b(width-1); s_btop=y2b(0); s_bbottom=y2b(height);
// the scroll bar should show body range -6 .. +6
s_fleft=(s_bleft+6)/12; s_fright=(s_bright+6)/12; if (s_fleft<0) s_fleft=0; if (s_fright>1) s_fright=1;
s_ftop=(s_btop+6)/12; s_fbottom=(s_bbottom+6)/12; if (s_ftop<0) s_ftop=0; if (s_fbottom>1) s_fbottom=1;
// so now show these ranges
SCROLLINFO si; ZeroMemory(&si,sizeof(si)); si.cbSize = sizeof(si);
si.fMask = SIF_DISABLENOSCROLL|SIF_PAGE|SIF_RANGE|SIF_POS;
si.nMin=0; si.nMax=10000;
si.nPage= (int)((s_fright-s_fleft)*10000);
si.nPos= (int)(s_fleft*10000);
if (s_fleft==0 && s_fright==1) {si.nMin=0; si.nMax=0; si.nPage=0; si.nPos=0;}
SetScrollInfo(chwnd,SB_HORZ,&si,TRUE);
si.nMin=0; si.nMax=10000;
si.nPage= (int)((s_fbottom-s_ftop)*10000);
si.nPos= (int)(s_ftop*10000);
if (s_ftop==0 && s_fbottom==1) {si.nMin=0; si.nMax=0; si.nPage=0; si.nPos=0;}
SetScrollInfo(chwnd,SB_VERT,&si,TRUE);
}
void TEditor::Scroll(bool horiz,int code,int pos)
{ double nbleft=s_bleft,nbright=s_bright,nbtop=s_btop,nbbottom=s_bbottom;
double bwidth=s_bright-s_bleft, bheight=s_bbottom-s_btop;
bool set=true;
if (horiz && code==SB_LINELEFT) {nbleft-=bwidth*0.1; nbright-=bwidth*0.1;}
else if (horiz && code==SB_PAGELEFT) {nbleft-=bwidth*0.9; nbright-=bwidth*0.9;}
else if (horiz && code==SB_LINERIGHT) {nbleft+=bwidth*0.1; nbright+=bwidth*0.1;}
else if (horiz && code==SB_PAGERIGHT) {nbleft+=bwidth*0.9; nbright+=bwidth*0.9;}
else if (!horiz && code==SB_LINEUP) {nbtop-=bheight*0.1; nbbottom-=bheight*0.1;}
else if (!horiz && code==SB_PAGEUP) {nbtop-=bheight*0.9; nbbottom-=bheight*0.9;}
else if (!horiz && code==SB_LINEDOWN) {nbtop+=bheight*0.1; nbbottom+=bheight*0.1;}
else if (!horiz && code==SB_PAGEDOWN) {nbtop+=bheight*0.9; nbbottom+=bheight*0.9;}
else if (horiz && (code==SB_THUMBTRACK || code==SB_THUMBPOSITION))
{ set=(code==SB_THUMBPOSITION); double dpos = ((double)pos)/10000.0;
nbleft = -6 + dpos*12;
nbright = nbleft + (s_bright-s_bleft);
}
else if (!horiz && (code==SB_THUMBTRACK || code==SB_THUMBPOSITION))
{ set=(code==SB_THUMBPOSITION); double dpos = ((double)pos)/10000.0;
nbtop = -6 + dpos*12;
nbbottom = nbtop + (s_bbottom-s_btop);
}
//
offx=(nbleft+nbright)*-0.5; offy=(nbtop+nbbottom)*-0.5;
Redraw();
if (set) SetScrollBars();
}
typedef struct {int parent; list<int> children;} TTreeNode;
typedef list<int> TPath;
int follow_path(vector<TTreeNode> &tree, int limb,int id)
{ int i=0; list<int>::const_iterator ci=tree[limb].children.begin();
while (i<id && ci!=tree[limb].children.end()) {i++; ci++;}
// if we couldn't find the specified child...
if (ci==tree[limb].children.end()) return limb;
return *ci;
}
int follow_path(vector<TTreeNode> &tree,int limb,const list<int> &path)
{ for (list<int>::const_iterator i=path.begin(); i!=path.end(); i++)
{ int id=*i;
limb = follow_path(tree,limb,id);
}
return limb;
}
void TEditor::Cursor(int dir)
{ int ilimbs=-1;
for (int i=0; i<(int)body->shapes.size(); i++)
{ if (body->shapes[i].limbs) ilimbs=i;
}
list<int> ss = sellimbs;
// if a shape had been selected, we'd still like the cursor keys to do something sensible...
if (sellimbs.size()==0)
{ if (selshapes.size()!=0)
{ stk::TShape &shape = body->shapes[selshapes.front()];
ss.clear();
for (int i=0; i<(int)shape.p.size(); i++)
{ ss.push_back(shape.p[i].i);
}
ss.sort(); ss.unique();
}
}
if (ss.size()==0 && (dir==0 || dir==2 || dir==1)) return;
//
// now we'll get tree information about everything
vector<TTreeNode> tree; tree.resize(body->nlimbs);
for (int i=0; i<body->nlimbs; i++)
{ int parent = body->limbs[i].root;
tree[i].parent = parent;
if (i!=0) tree[parent].children.push_back(i);
}
// and express the selected things as indexed paths.
list<TPath> paths;
for (list<int>::const_iterator i=ss.begin(); i!=ss.end(); i++)
{ TPath pa; int limb=*i;
while (limb!=0)
{ int parent = body->limbs[limb].root;
int sub=-1, j=0; for (list<int>::const_iterator ji=tree[parent].children.begin(); ji!=tree[parent].children.end(); ji++,j++) {if (*ji==limb) sub=j;}
LUASSERT(sub!=-1); pa.push_front(sub); limb=parent;
}
paths.push_back(pa);
}
TPath hitpath;
if (hit.n!=-1)
{ int limb=hit.n; while (limb!=0)
{ int parent = body->limbs[limb].root;
int sub=-1, j=0; for (list<int>::const_iterator ji=tree[parent].children.begin(); ji!=tree[parent].children.end(); ji++,j++) {if (*ji==limb) sub=j;}
LUASSERT(sub!=-1); hitpath.push_front(sub); limb=parent;
}
}
//
// now we have what we need!
int sel=-1;
if (dir==0 || dir==2) // left/right navigation
{ if (paths.size()==0) return;
else if (paths.size()==1 || hit.n!=-1) // cycle within the current subtree
{ TPath p2; if (hit.n!=-1) p2=hitpath; else p2=paths.front();
int last = p2.back(); p2.pop_back();
sel = follow_path(tree,0,p2);
int nchildren = (int)tree[sel].children.size();
if (dir==0) last=(last+1)%nchildren; else last=(last+nchildren-1)%nchildren;
sel=follow_path(tree,sel,last);
}
else // for multisel, when hit left/right, pick the leftmost/rightmost one
{ sel=0;
while (paths.size()>0)
{ int max=-2; list<TPath>::iterator i=paths.begin();
while (i!=paths.end())
{ int ci=i->front(); i->pop_front();
if (dir==0) {if (max==-2) max=ci; else if (ci>max) max=ci;}
else {if (max==-2) max=ci; else if (ci<max) max=ci;}
if (i->size()==0) i=paths.erase(i); else i++;
sel=follow_path(tree,sel,max);
}
}
}
}
else if (dir==1) // for navigation up
{ if (paths.size()==0) return;
else if (paths.size()==1 || hit.n!=-1) // for onesel, pick its parent
{ TPath p2; if (hit.n!=-1) p2=hitpath; else p2=paths.front();
if (p2.size()<=1) return;
p2.pop_back();
sel = follow_path(tree,0,p2);
}
else // for multisel, pick the topiest
{ const TPath *p=0; int len=-2;
for (list<TPath>::const_iterator i=paths.begin(); i!=paths.end(); i++)
{ if (len==-2) {p = &(*i); len=p->size();}
else {if ((int)i->size()<len) {p=&(*i);len=p->size();}}
}
sel = follow_path(tree,0,*p);
}
}
else // dir=3, for navigation down
{ if (paths.size()==0) // for nosel, pick the first child of root
{ sel = follow_path(tree,0,0);
}
else if (hit.n!=-1)
{ sel = follow_path(tree,0,hitpath);
sel = follow_path(tree,sel,0);
if (sel==-1) return;
}
else if (paths.size()==1) // for onesel, pick its first child
{ sel = follow_path(tree,0,paths.front());
sel = follow_path(tree,sel,0);
if (sel==-1) return;
}
else // for multisel, pick the deepest
{ const TPath *p=0; int len=-2;
for (list<TPath>::const_iterator i=paths.begin(); i!=paths.end(); i++)
{ if (len==-2) {p=&(*i); len=p->size();}
else {if ((int)i->size()<len) {p=&(*i);len=p->size();}}
}
sel = follow_path(tree,0,*p);
}
}
//
bool shift = GetAsyncKeyState(VK_SHIFT)<0;
if (!shift)
{ sellimbs.clear(); selshapes.clear(); hit.n=-1; hit.s=-1; hit.type=htMiss;
if (sel!=-1) {sellimbs.push_back(sel); hit.n=sel; hit.s=ilimbs;}
}
else
{ if (sel==-1) return;
sellimbs.push_back(sel); sellimbs.sort(); sellimbs.unique();
hit.n=sel; hit.s=ilimbs;
}
Redraw();
}
void TEditor::FinishSeling()
{ mode=mNothing;
double x0=zoomx0, y0=zoomy0, x1=zoomx, y1=zoomy;
if (zoomx<zoomx0) {x0=zoomx; x1=zoomx0;}
if (zoomy<zoomy0) {y0=zoomy; y1=zoomy0;}
x0=x2b((int)x0); y0=y2b((int)y0); x1=x2b((int)x1); y1=y2b((int)y1);
// so now x0,y0 - x1,y1 is our selecting rectangle. We toggle the
// selectidity of stuff inside it. They have to be wholly inside it.
vector<bool> lbitmap, sbitmap; lbitmap.resize(body->nlimbs); sbitmap.resize(body->shapes.size());
for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++) lbitmap[*i]=true;
for (list<int>::const_iterator i=selshapes.begin();i!=selshapes.end();i++) sbitmap[*i]=true;
//
list<int> nl, ns;
ObjectsInRect(x0,y0,x1,y1,nl,ns);
//
for (list<int>::const_iterator i=nl.begin(); i!=nl.end(); i++) lbitmap[*i] = !lbitmap[*i];
for (list<int>::const_iterator i=ns.begin(); i!=ns.end(); i++) sbitmap[*i] = !sbitmap[*i];
sellimbs.clear(); selshapes.clear();
for (int i=0; i<body->nlimbs; i++) {if (lbitmap[i]) sellimbs.push_back(i);}
for (int i=0; i<(int)body->shapes.size(); i++) {if (sbitmap[i]) selshapes.push_back(i);}
hit.n=-1; hit.s=-1; hit.type=htMiss;
Redraw();
UpdateMenus();
}
void TEditor::Zoom(int dir)
{ if (dir==1) zoom*=2;
else if (dir==-1) zoom*=0.5;
else
{ offx=0; offy=0;
double w=width, h=height;
zoom = w/12; if (h/12<zoom) zoom=h/12;
}
if (zoom<1) zoom=1;
if (zoom>1000000) zoom=1000000;
Redraw(); SetCursor();
SetScrollBars();
}
void TEditor::FinishZooming()
{ mode=mNothing;
double x0=zoomx0, y0=zoomy0, x1=zoomx, y1=zoomy;
if (zoomx<zoomx0) {x0=zoomx; x1=zoomx0;}
if (zoomy<zoomy0) {y0=zoomy; y1=zoomy0;}
double dx=x1-x0, dy=y1-y0;
double dd=sqrt(dx*dx+dy*dy);
if (dd<10)
{ zoom=zoom*0.5; if (zoom<1) zoom=1;
Recalc(0); Redraw(); SetCursor(); SetScrollBars(); ShowHint("ZOOM mode. (Right-click to change mode)"); return;
}
//
x0=x2b((int)x0); y0=y2b((int)y0); x1=x2b((int)x1); y1=y2b((int)y1);
double w=width, h=height;
offx=(x0+x1)*-0.5; offy=(y0+y1)*-0.5;
double zoom1=w/(x1-x0), zoom2=h/(y1-y0);
zoom=zoom1; if (zoom2<zoom) zoom=zoom2;
if (zoom>1000000) zoom=1000000;
Recalc(0);
Redraw(); SetCursor();
SetScrollBars();
//
ShowHint("ZOOM mode. (Right-click to change mode)");
}
void TEditor::FinishAngling()
{ mode=mNothing;
ismodified=true;
ShowHint("");
}
void TEditor::FinishSpringing()
{ mode=mNothing;
ismodified=true;
ShowHint("");
}
void TEditor::RepositioningMove(int n,int mx,int my,bool suppresscalcdraw)
{ TLimb &limb=body->limbs[n];
bool gsnap=false; if (UserGrid) gsnap=SnapToGrid(&mx,&my);
double x=x2b(mx), y=y2b(my);
TAdjAngle a=AngleFromOff(x-limb.x0,y-limb.y0,limb.ang0,limb.aoff,limb.ascale);
if ((limb.type==0 || limb.type==1) && limb.chan==4 && limb.band==0) // fixed. rootang+f.
{ a=AngleNearbyFromOff(x-limb.x0,y-limb.y0,limb.ang0,limb.ascale);
double ang=a.screenang; ang-=limb.aoff; if (limb.aisoff) ang-=body->limbs[limb.root].ang;
// We'll now fix it up so it's close to the old value. In fact, AngleNearbyFromOff was
// supposed to do that, but it's a bit hard to debug...
// ang is the angle. But it could be (say) 5.0, which could be interpreted as +5 or as -1.28.
// so we will pick whichever one is closer to ascale.
while (ang<0) ang+=2*pi; while (ang>2*pi) ang-=2*pi;
double ang_other = ang-2*pi;
double d=ang-limb.ascale, d_other=ang_other-limb.ascale;
d=d*d; d_other=d_other*d_other;
if (d_other<d) ang=ang_other;
//
limb.ascale=ang*1.1; if (limb.ascale<-2*pi) limb.ascale=-2*pi;
if (limb.ascale>2*pi) limb.ascale=2*pi; // so that ascale indicates the direction of the arc
while (ang<-2*pi) ang+=2*pi; while (ang>2*pi) ang-=2*pi;
limb.f=ang; if (n!=0 && !gsnap) limb.f=SnapAngle(limb.f,true);
limb.length=a.relrad; limb.lmin=limb.length*0.4;
ShowHint(StringAng(limb.f)+", "+StringLength(a.relrad));
}
else if (limb.type==0 || limb.type==1) // normal. dragging f within an ascale
{ if (!a.isin) return;
limb.f=a.f; limb.length=a.relrad; limb.lmin=limb.length*0.4;
ShowHint(StringFrac(limb.f)+", "+StringLength(a.relrad));
SetF(n,limb.chan,limb.band,limb.f,suppresscalcdraw);
return;
}
else if (limb.type==2 || limb.type==3) // a spring. dragging the point, and so adjusting angle and f
{ double ang=a.screenang; if (limb.aisoff) ang-=body->limbs[limb.root].ang;
while (ang<0) ang+=2*pi; while (ang>2*pi) ang-=2*pi;
if (n!=0 && !gsnap) ang=SnapAngle(ang,true);
limb.aspring=ang-limb.aoff;
double lf=a.relrad;
if (limb.chan==4 && limb.band==0) // a fixed: the limits are of no concern to us
{ //if (lf>limb.length) limb.length=lf*1.1;
if (lf<limb.lmin) limb.lmin=lf*0.9;
limb.length=lf; limb.f=1;
ShowHint(StringAng(ang)+", "+StringLength(lf));
}
else
{ if (lf>limb.length) lf=limb.length; if (lf<limb.lmin) lf=limb.lmin;
limb.f = (lf-limb.lmin) / (limb.length-limb.lmin);
limb.f = 1-limb.f;
ShowHint(StringAng(ang)+", "+StringFrac(limb.f));
}
}
ismodified=true;
if (!suppresscalcdraw) {Recalc(n); Redraw(); SetCursor();}
}
void TEditor::SetF(int n, int chan,int band, double f,bool suppresscalcdraw)
{ if (chan==4) return;
vector<bool> ancestors; ancestors.resize(body->nlimbs);
while (n!=0) {ancestors[n]=true; n=body->limbs[n].root;}
for (int i=0; i<body->nlimbs; i++)
{ int achan=body->limbs[i].chan, aband=body->limbs[i].band;
if (achan==chan && aband==band && !ancestors[i])
{ body->limbs[i].f=f;
if (body->limbs[i].negative) body->limbs[i].f = 1.0-body->limbs[i].f;
}
}
if (!suppresscalcdraw) {Recalc(0); Redraw(); SetCursor();}
}
void TEditor::Unselect()
{ mode=mNothing;
if (hit.type!=htRoot) {Redraw();SetCursor();return;}
// If user clicked on the selected root, that changes its aoff mode
// but we want to preserve the effective angle
int root=body->limbs[hit.n].root;
if (root==0) {Redraw(); SetCursor();return;}
double rang=body->limbs[root].ang;
//double ang=body->limbs[hit.n].aoff;
if (body->limbs[hit.n].aisoff)
{ body->limbs[hit.n].aisoff=false;
body->limbs[hit.n].aoff += rang;
}
else
{ body->limbs[hit.n].aisoff=true;
body->limbs[hit.n].aoff -= rang;
}
ismodified=true;
Redraw();
SetCursor();
ShowHint("");
}
void TEditor::FinishCreateCorner()
{ stk::TShape &shape = body->shapes[hit.s];
if (cortarget.i==-1)
{ if (mode==mCreateCornerDragging) {cori=-1; mode=mNothing; Redraw(); return;}
// upon move, failure is only allowed if the thing will be left with at least two different points
TJointRef pt = shape.p[0];
for (int i=1; i<(int)shape.p.size(); i++)
{ if (shape.p[i]!=pt) {cori=-1; mode=mNothing; Redraw(); return;}
}
cortarget=corotarget; // otherwise, we just create back the point we removed when we started dragging
}
if (mode==mCreateCornerDragging) MarkUndo();
mode=mNothing;
// we will update the shape with a new point, unless it's a duplicate of its neighbour
ismodified=true;
bool isdup=false;
if (shape.p[cori]==cortarget) isdup=true;
if (shape.p[(cori+1)%shape.p.size()]==cortarget) isdup=true;
vector<TJointRef> np; np.reserve(shape.p.size()+1);
for (int i=0; i<cori+1; i++) np.push_back(shape.p[i]);
if (!isdup) np.push_back(cortarget);
for (int i=cori+1; i<(int)shape.p.size(); i++) np.push_back(shape.p[i]);
shape.p = np;
hit.si=cori; hit.type=htLine;
cori=-1;
Redraw();
UpdateMenus();
}
void TEditor::FinishCreate()
{ MarkUndo();
sellimbs.clear(); selshapes.clear(); hit.n=-1; hit.s=-1; hit.type=htMiss;
if (rubend.i==-1) // did we just create a normal limb?
{ int n=body->CreateLimb(rubber); int mx=b2x(rubber.x), my=b2y(rubber.y);
Recalc(n);
if (rubber.chan==4 && rubber.band==0) RepositioningMove(n,mx,my,false);
// that's a hack. Before, it was putting the newly created fixed limb in the wrong place
hit.n=n; hit.type=htSpot; // select the thing we've just created
sellimbs.push_back(n);
}
else // or we created a shape (i.e. a line)
{ stk::TShape shape; shape.brush.type=ctRGB; shape.brush.dtype=ctRGB; shape.brush.rgb=RGBCOLOR(defcols[cYellow].r,defcols[cYellow].g,defcols[cYellow].b);
shape.line.type=ctRGB; shape.line.dtype=ctRGB; shape.line.rgb=RGBCOLOR(128,128,128); shape.thickness=1;
shape.limbs=false; shape.balternate=false;
TJointRef j(rubber.root,false); shape.p.push_back(j);
shape.p.push_back(rubend);
shape.linestyle=nextlinestyle;
TStyle style=StyleFromName(shape.linestyle); if (style.name!="")
{ shape.line=style.limb.color; shape.thickness=style.limb.thickness;
}
shape.fillstyle=nextfillstyle;
style=StyleFromName(shape.fillstyle); if (style.name!="")
{ shape.brush=style.shape.brush;
if (shape.brush.type==ctBitmap)
{ for (int i=0; i<(int)body->bmps.size(); i++)
{ if (StringLower(shape.brush.bitmap)==StringLower(body->bmps[i].name)) shape.brush.bindex=i;
}
}
}
body->shapes.push_back(shape);
// and now reset our rubber
rubend=-1;
// and select the thing we've just created
hit.n=-1; hit.s=(int)body->shapes.size()-1; hit.sf=0; hit.si=0; hit.type=htLine;
selshapes.push_back(hit.s);
}
mode=mNothing;
ismodified=true;
UpdateMenus();
Redraw();
ShowHint("CREATE mode. (Right-click to go back to EDIT mode)");
}
void TEditor::FinishRepositioning()
{ mode=mNothing;
ismodified=true;
Redraw();
ShowHint("");
}
void TEditor::Size(int awidth,int aheight)
{ width=awidth; height=aheight;
int cx=GetSystemMetrics(SM_CXSCREEN), cy=GetSystemMetrics(SM_CYSCREEN);
BITMAP bmp; GetObject(memBM,sizeof(bmp),&bmp);
if (bmp.bmWidth<width || bmp.bmHeight<height)
{ int width2=min(width*3/2,cx), height2=min(height*3/2,cy);
SelectObject(memDC,oldBM);
DeleteObject(memBM);
HDC hdc=GetDC(chwnd);
memBM = CreateCompatibleBitmap(hdc,width2,height2);
ReleaseDC(chwnd,hdc);
oldBM = (HBITMAP)SelectObject(memDC,memBM);
}
Recalc(0);
SetScrollBars();
}
void TEditor::Invert()
{ WhitePrint = !WhitePrint;
RegSaveUser();
Redraw();
UpdateMenus();
}
void TEditor::Animate()
{ mode=mNothingTesting;
timeStart=GetTickCount(); timePrev=timeStart;
samplei = rand()%3;
unsigned int maxtime = (samplesize[samplei]/12)*41;
timeStart += rand()%maxtime;
idTimer=SetTimer(mhwnd,1,100,NULL);
}
void TEditor::StopAnimate()
{ if (idTimer!=0) KillTimer(mhwnd,idTimer); idTimer=0;
mode=mNothing;
Tick(true);
}
void TEditor::Tick(bool)
{ unsigned int now=GetTickCount();
unsigned int diff=now-timePrev; if (diff<(unsigned int)(1000/body->fps)) return;
// our notional standard is 10ms between frames. We use this to scale the cumulative stuff
double cmul=((double)diff)/10.0;
//
timePrev=now;
unsigned int time=now-timeStart;
unsigned int off = (time/41)%samplesize[samplei];
unsigned char *sd = sampledat[samplei]+off*12;
double freq[3][6];
for (int chan=0; chan<2; chan++)
{ for (int band=0; band<6; band++)
{ unsigned char s = sd[chan*6+band];
double d = ((double)s)/255.0;
freq[chan][band]=d;
}
freq[2][0]=freq[0][3]; freq[2][1]=freq[1][4];
}
// do the limb positions
body->AssignFreq(freq,cmul);
body->Recalc(); body->RecalcEffects(true);
Redraw();
}
void TEditor::DrawPiePart(HDC hdc,int x0,int y0,double length,double ang0,double ang,double ang1)
{ int ilength=(int)(length+0.5);
double angA,angB,angC,angD; // fill in A->B, line C->D. All will be anticlockwise.
if (ang1<=ang0) {angA=ang0; angB=ang; angC=ang; angD=ang1;}
else {angA=ang; angB=ang0; angC=ang1; angD=ang;}
int dxA=x0+(int)(cos(angA)*length), dyA=y0+(int)(sin(angA)*length);
int dxB=x0+(int)(cos(angB)*length), dyB=y0+(int)(sin(angB)*length);
int dxC=x0+(int)(cos(angC)*length), dyC=y0+(int)(sin(angC)*length);
int dxD=x0+(int)(cos(angD)*length), dyD=y0+(int)(sin(angD)*length);
int ddAB=(dxB-dxA)*(dxB-dxA)+(dyB-dyA)*(dyB-dyA);
int ddCD=(dxD-dxC)*(dxD-dxC)+(dyD-dyC)*(dyD-dyC);
if (ddAB<100 && angA-angB<pi) {POINT pt[]={{x0,y0},{dxA,dyA},{dxB,dyB}}; Polygon(hdc,pt,3);}
else Pie(hdc,x0-ilength,y0-ilength,x0+ilength,y0+ilength, dxA,dyA, dxB,dyB);
if (ddCD<100 && angC-angD<pi) {MoveToEx(hdc,dxC,dyC,NULL); LineTo(hdc,dxD,dyD);}
else Arc(hdc,x0-ilength,y0-ilength,x0+ilength,y0+ilength, dxC,dyC, dxD,dyD);
}
void TEditor::DrawLinePart(HDC hdc,double thick,double ang,int x0,int y0,int x1,int y1,int x2,int y2)
{ double ddx=cos(ang+0.5*pi)*thick, ddy=sin(ang+0.5*pi)*thick;
int dx=(int)ddx, dy=(int)ddy;
POINT pt[5];
pt[0].x=x0+dx; pt[0].y=y0+dy;
pt[1].x=x1+dx; pt[1].y=y1+dy;
pt[2].x=x1-dx; pt[2].y=y1-dy;
pt[3].x=x0-dx; pt[3].y=y0-dy;
Polygon(hdc,pt,4);
pt[0].x=x2+dx; pt[0].y=y2+dy;
pt[3].x=x2-dx; pt[3].y=y2-dy;
pt[4]=pt[0];
Polyline(hdc,pt,5);
}
void TEditor::DrawPie(HDC hdc,TLimb &dst,int sp,bool fillall)
{ if (dst.chan==4) return;
COLORREF col=RGB(0,0,0),col2=RGB(0,0,0); int c1=dst.band*15+20, c2=dst.band*20+130;
if (dst.chan==0) col=RGB(c1,c1,c2);
else if (dst.chan==1) col=RGB(c2,c1,c1);
else if (dst.chan==2) {col=RGB(c1,c1,c2); col2=RGB(c2,c1,c1);}
else if (dst.chan==3) col=RGB(c1,c2,c1);
else col=RGB(128,128,128);
HPEN hPiePen=CreatePen(PS_SOLID,0,col);
LOGBRUSH lb; lb.lbColor=col; lb.lbStyle=BS_SOLID; HBRUSH hPieBrush=CreateBrushIndirect(&lb);
HPEN hPiePen2=NULL; HBRUSH hPieBrush2=NULL;
HPEN holdp=(HPEN)SelectObject(hdc,hPiePen);
HBRUSH holdb=(HBRUSH)SelectObject(hdc,hPieBrush);
double dsp=sp;
//
// A straightforward angle limb. Draw filled:aoff->ang, empty:ang->ascale. fillall means fill it all
if ((dst.type==0 || dst.type==1) && (dst.chan==0 || dst.chan==1 || dst.chan==3))
{ if (!dst.negative) DrawPiePart(hdc,b2x(dst.x0),b2y(dst.y0),dsp,dst.ang0,fillall?dst.ang1:dst.ang,dst.ang1);
else DrawPiePart(hdc,b2x(dst.x0),b2y(dst.y0),dsp,dst.ang1,fillall?dst.ang0:dst.ang,dst.ang0);
}
//
// A straightforward spring limb. Draw filled:length->f, empty:f->lmin.
if ((dst.type==2 || dst.type==3) && (dst.chan==0 || dst.chan==1 || dst.chan==3))
{ int x[3],y[3]; double lf=dst.lmin*dst.f+dst.length*(1-dst.f);
x[0]=b2x(dst.x0+dst.lmin*cos(dst.ang)); y[0]=b2y(dst.y0+dst.lmin*sin(dst.ang));
x[1]=b2x(dst.x0+lf*cos(dst.ang)); y[1]=b2y(dst.y0+lf*sin(dst.ang));
x[2]=b2x(dst.x0+dst.length*cos(dst.ang)); y[2]=b2y(dst.y0+dst.length*sin(dst.ang));
if (!dst.negative) DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],fillall?x[0]:x[1],fillall?y[0]:y[1],x[0],y[0]);
else DrawLinePart(hdc,dsp/2,dst.ang,x[0],y[0],fillall?x[2]:x[1],fillall?y[2]:y[1],x[2],y[2]);
}
//
// A difference angle limb.
// filled:middle->ang (in either col1 or col2); empty:ang->aoff, middle->ascale
// fillall means filled1:middle->aoff, filled2:middle->ascale
if ((dst.type==0 || dst.type==1) && dst.chan==2)
{ double angMin,angLeft,angMid,angRight,angMax; // min->left and max->right are hollow; mid->left and mid->right are full
angMid=(dst.ang0+dst.ang1)/2; angMin=dst.ang0; angMax=dst.ang1;
if (dst.f>=0.5) {angLeft=angMid; angRight=dst.ang;}
else {angLeft=dst.ang; angRight=angMid;}
if (fillall) {angLeft=angMin; angRight=angMax;}
//
hPiePen2=CreatePen(PS_SOLID,0,col2);
lb.lbColor=col2; hPieBrush2=CreateBrushIndirect(&lb);
if (!dst.negative) DrawPiePart(hdc,b2x(dst.x0),b2y(dst.y0),dsp,angMid,angLeft,angMin);
else DrawPiePart(hdc,b2x(dst.x0),b2y(dst.y0),dsp,angMid,angRight,angMax);
SelectObject(hdc,hPiePen2); SelectObject(hdc,hPieBrush2);
if (!dst.negative) DrawPiePart(hdc,b2x(dst.x0),b2y(dst.y0),dsp,angMid,angRight,angMax);
else DrawPiePart(hdc,b2x(dst.x0),b2y(dst.y0),dsp,angMid,angLeft,angMin);
}
//
// A difference spring limb. filled: middle->f (in either col1 or col2); empty: lmin->middle, f->length
// filledall means filled1:middle->lmin, filled2:middle->lmax
// Oops! actually, I reversed the sense of f.
if ((dst.type==2 || dst.type==3) && dst.chan==2)
{ int x[4],y[4]; double lf=dst.lmin*dst.f+dst.length*(1-dst.f), lm=dst.lmin*0.5+dst.length*0.5;
x[0]=b2x(dst.x0+dst.lmin*cos(dst.ang)); y[0]=b2y(dst.y0+dst.lmin*sin(dst.ang));
x[1]=b2x(dst.x0+lf*cos(dst.ang)); y[1]=b2y(dst.y0+lf*sin(dst.ang));
x[2]=b2x(dst.x0+lm*cos(dst.ang)); y[2]=b2y(dst.y0+lm*sin(dst.ang));
x[3]=b2x(dst.x0+dst.length*cos(dst.ang)); y[3]=b2y(dst.y0+dst.length*sin(dst.ang));
hPiePen2=CreatePen(PS_SOLID,0,col2);
lb.lbColor=col2; hPieBrush2=CreateBrushIndirect(&lb);
if (fillall)
{ if (!dst.negative) DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[0],y[0],x[0],y[0]);
else DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[3],y[3],x[3],y[3]);
SelectObject(hdc,hPiePen2); SelectObject(hdc,hPieBrush2);
if (!dst.negative) DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[3],y[3],x[3],y[3]);
else DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[0],y[0],x[0],y[0]);
}
else if (dst.f>=0.5)
{ if (!dst.negative) DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[1],y[1],x[0],y[0]);
else DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[2],y[2],x[3],y[3]);
SelectObject(hdc,hPiePen2); SelectObject(hdc,hPieBrush2);
if (!dst.negative) DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[2],y[2],x[3],y[3]);
else DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[1],y[1],x[0],y[0]);
}
else
{ if (!dst.negative) DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[2],y[2],x[0],y[0]);
else DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[1],y[1],x[3],y[3]);
SelectObject(hdc,hPiePen2); SelectObject(hdc,hPieBrush2);
if (!dst.negative) DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[1],y[1],x[3],y[3]);
else DrawLinePart(hdc,dsp/2,dst.ang,x[2],y[2],x[2],y[2],x[0],y[0]);
}
}
//
SelectObject(hdc,holdb);
SelectObject(hdc,holdp);
DeleteObject(hPiePen);
DeleteObject(hPieBrush);
if (hPiePen2!=NULL) DeleteObject(hPiePen2);
if (hPieBrush2!=NULL) DeleteObject(hPieBrush2);
}
class TAutoPen
{ public:
HPEN hpen,hprev;
bool set(double thickness,bool sel,bool vis,int r,int g,int b)
{ if (r==-1) {r=avert?0:255; g=avert?0:255; b=avert?0:255;}
if (r==255 && g==255 && b==255) {r=avert?0:255; g=avert?0:255; b=avert?0:255;}
if (thickness==athick && sel==asel && vis==avis && r==ar && g==ag && b==ab && hpen!=0) return false;
if (hpen!=0)
{ if (hprev!=0) DeleteObject(hprev);
hprev=hpen;
}
int style = vis?PS_SOLID:PS_DOT;
int width=0;
if (vis)
{ double tt=thickness;
tt = tt+1.0;
tt = tt-1.0;
if (tt<0.5) width=0;
else if (tt<1.5) width=1;
else width=2;
if (!avert) width*=2;
}
if (sel&&vis) {width+=avert?1:2;}
if (style==PS_DOT) width=1;
if (!vis && !ShowInvisibles) style=PS_NULL;
hpen = CreatePen(style, width, RGB(r,g,b));
athick=thickness; asel=sel; avis=vis; ar=r; ag=g; ab=b;
return true;
}
TAutoPen(bool vert) {hpen=0; hprev=0; avert=vert;}
~TAutoPen() {if (hpen!=0) DeleteObject(hpen); hpen=0; if (hprev!=0) DeleteObject(hprev); hprev=0;}
protected:
double athick; bool asel,avis; int ar,ag,ab; bool avert;
};
bool TEditor::Draw(HDC hwndc, string *err)
{ bool fail=false;
//
HDC hdc=memDC;
SetGraphicsMode(hdc,GM_ADVANCED);
SetStretchBltMode(hdc,COLORONCOLOR);
HDC tdc=CreateCompatibleDC(hwndc); HGDIOBJ holdt=0; // for any bitmaps we might draw
//
bool vert=WhitePrint;
if (body->limbs[0].color.rgb.r>240 && body->limbs[0].color.rgb.g>240 && body->limbs[0].color.rgb.b>240) vert=true;
HPEN hAnglePen=CreatePen(PS_SOLID,0,RGB(64,192,222));
HPEN hPlusPen=CreatePen(PS_SOLID,0,RGB(212,32,32));
TAutoPen lpen(vert);
HPEN hRubberPen=CreatePen(PS_DOT,0,RGB(vert?0:240,vert?0:240,vert?0:240));
HPEN hAnchorPen=CreatePen(PS_SOLID,0,RGB(182,182,36));
HPEN hBorderPen=CreatePen(PS_DOT,0,RGB(182,182,182));
LOGBRUSH lb; lb.lbColor=RGB(212,32,32); lb.lbStyle=BS_SOLID; HBRUSH hAngleBrush=CreateBrushIndirect(&lb);
HBRUSH holdb=(HBRUSH)SelectObject(hdc,GetStockObject(BLACK_BRUSH));
HPEN holdp=(HPEN)SelectObject(hdc,GetStockObject(BLACK_PEN));
//
RECT rc={0,0,width,height};
lb.lbColor = RGB(body->limbs[0].color.rgb.r, body->limbs[0].color.rgb.g, body->limbs[0].color.rgb.b);
HBRUSH hbackbrush = CreateBrushIndirect(&lb);
if (WhitePrint) SetBkColor(hdc,RGB(255,255,255)); else SetBkColor(hdc,lb.lbColor);
if (WhitePrint) FillRect(hdc,&rc,(HBRUSH)GetStockObject(WHITE_BRUSH));
else FillRect(hdc,&rc,hbackbrush);
DeleteObject(hbackbrush);
Scale(-5,-5,(int*)&rc.left,(int*)&rc.top); Scale(5,5,(int*)&rc.right,(int*)&rc.bottom);
if (hbackdrop!=0)
{ HDC htempdc=CreateCompatibleDC(hdc); HGDIOBJ hold=SelectObject(htempdc,hbackdrop);
BITMAP bmp; GetObject(hbackdrop,sizeof(bmp),&bmp);
StretchBlt(hdc,rc.left,rc.top,rc.right-rc.left,rc.bottom-rc.top,htempdc,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
SelectObject(htempdc,hold); DeleteObject(htempdc);
}
SelectObject(hdc,hBorderPen); SelectObject(hdc,GetStockObject(NULL_BRUSH));
Rectangle(hdc,rc.left,rc.top,rc.right,rc.bottom);
if (UserGrid)
{ // we'll find the interval (1,0.1,...) which gives a nice spacing
double interval=1.0; int si;
for (;;)
{ si = b2x(interval)-b2x(0); if (si<60) break;
interval /= 5;
si = b2x(interval)-b2x(0); if (si<60) break;
interval /= 2;
}
if (si>4)
{ int lx=b2x(-5), ly=b2y(-5), rx=b2x(5), ry=b2y(5);
while (lx<0) lx+=si; while (rx>width) rx-=si;
while (ly<0) ly+=si; while (ry>height) ry-=si;
for (int y=ly; y<ry; y+=si)
{ for (int x=lx; x<rx; x+=si)
{ SetPixel(hdc,x,y,RGB(182,182,182));
}
}
}
}
int n;
//
// First draw any anchors
SelectObject(hdc,hAnchorPen);
for (n=1; n<body->nlimbs; n++)
{ TLimb &limb=body->limbs[n];
int x=b2x(limb.x), y=b2y(limb.y); int aw=AnchorLength/2, ao=AnchorOffLength;
if (limb.anchor==1) {MoveToEx(hdc,x-aw,y-ao,NULL); LineTo(hdc,x+aw,y-ao);} // north
else if (limb.anchor==2) {MoveToEx(hdc,x+ao,y-aw,NULL); LineTo(hdc,x+ao,y+aw);} // east
else if (limb.anchor==3) {MoveToEx(hdc,x-aw,y+ao,NULL); LineTo(hdc,x+aw,y+ao);} // south
else if (limb.anchor==4) {MoveToEx(hdc,x-ao,y-aw,NULL); LineTo(hdc,x-ao,y+aw);} // west
}
//
// Now maybe draw the current line's editing pie
list<TLimb*> sels;
if (mode==mCreateDragging) {if (rubend.i==-1) sels.push_back(&rubber);}
else
{ for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++) sels.push_back(&body->limbs[*i]);
}
for (list<TLimb*>::const_iterator si=sels.begin(); si!=sels.end(); si++) DrawPie(hdc,**si,SelPieLength,false);
//
// Draw angle pies on every limb
for (n=1; n<body->nlimbs && ShowAngles; n++) DrawPie(hdc,body->limbs[n],PieLength,true);
//
// Draw the shapes and lines. In mode==mCreateDragging we also draw the rubber.
//
TEffPt ept;
for (int sn=0; sn<(int)body->shapes.size(); sn++)
{ const stk::TShape &shape = body->shapes[sn];
if (!shape.limbs)
{ SetPolyFillMode(hdc,shape.balternate?ALTERNATE:WINDING);
bool heavy=false;
for (list<int>::const_iterator si=selshapes.begin(); si!=selshapes.end(); si++) {if (sn==*si) heavy=true;}
bool simplecircle = (shape.p.size()==2 && shape.p[0].i==shape.p[1].i && shape.p[0].ar!=shape.p[1].ar && body->limbs[shape.p[0].i].type==3);
if (shape.brush.dtype==ctBitmap && (shape.brush.bindex<0 || shape.brush.bindex>=(int)body->bmps.size())) {fail=true; if (err!=0) *err="bindex";}
if (simplecircle && shape.brush.dtype==ctBitmap && shape.brush.bindex!=-1)
{ TLimb &limb = body->limbs[shape.p[0].i];
double dx=limb.x-limb.x0,dy=limb.y-limb.y0, rad=sqrt(dx*dx+dy*dy);
int x0=b2x(limb.x0-rad), y0=b2y(limb.y0-rad), x1=b2x(limb.x0+rad), y1=b2y(limb.y0+rad);
TBmp &bmp = body->bmps[shape.brush.bindex];
// adjust the rect so the bitmap is kept proportional
double f=((double)bmp.bwidth)/((double)bmp.bheight);
if (f>1) {int cy=(y0+y1)/2, h=y1-y0; h=(int)(((double)h)/f); y0=cy-h/2; y1=cy+h/2;}
else if (f<1) {int cx=(x0+x1)/2, w=x1-x0; w=(int)(((double)w)*f); x0=cx-w/2; x1=cx+w/2;}
XFORM mat; FLOAT ang=(FLOAT)(limb.ang);
FLOAT c=(FLOAT)cos(ang), s=(FLOAT)sin(ang);
FLOAT cx=(FLOAT)(x0+(x1-x0)/2), cy=(FLOAT)(y0+(y1-y0)/2);
mat.eM11=c; mat.eM12=s; mat.eM21=-s; mat.eM22=c;
mat.eDx=cx+cy*s-cx*c; mat.eDy=cy-cy*c-cx*s;
// If we're too zoomed in, then we won't draw the bitmap.
bool toobig = (x1-x0>width*2 || y1-y0>height*2);
FLOAT xtl=(FLOAT)x0, xbl=(FLOAT)x0, ytl=(FLOAT)y0, ytr=(FLOAT)y0, xtr=(FLOAT)x1, xbr=(FLOAT)x1, ybl=(FLOAT)y1, ybr=(FLOAT)y1;
FLOAT xtl2=xtl*mat.eM11+ytl*mat.eM21+mat.eDx, ytl2=xtl*mat.eM12+ytl*mat.eM22+mat.eDy;
FLOAT xtr2=xtr*mat.eM11+ytr*mat.eM21+mat.eDx, ytr2=xtr*mat.eM12+ytr*mat.eM22+mat.eDy;
FLOAT xbl2=xbl*mat.eM11+ybl*mat.eM21+mat.eDx, ybl2=xbl*mat.eM12+ybl*mat.eM22+mat.eDy;
FLOAT xbr2=xbr*mat.eM11+ybr*mat.eM21+mat.eDx, ybr2=xbr*mat.eM12+ybr*mat.eM22+mat.eDy;
LONG ixtl=(LONG)xtl2, ixtr=(LONG)xtr2, ixbl=(LONG)xbl2, ixbr=(LONG)xbr2;
LONG iytl=(LONG)ytl2, iytr=(LONG)ytr2, iybl=(LONG)ybl2, iybr=(LONG)ybr2;
bool offthescreen = (ixtr<0 && ixbr<0) || (ixtl>width && ixbl>width);
offthescreen |= (iybl<0 && iybr<0) || (iytl>height && iytr>height);
if (!offthescreen && (toobig || (WhitePrint && bmp.hbmask==0)))
{ POINT pt[5]; pt[0].x=ixtl; pt[0].y=iytl; pt[1].x=ixtr; pt[1].y=iytr;
pt[2].x=ixbr; pt[2].y=iybr; pt[3].x=ixbl; pt[3].y=iybl;
SelectObject(hdc,GetStockObject(LTGRAY_BRUSH));
SelectObject(hdc,GetStockObject(NULL_PEN));
Polygon(hdc,pt,4);
}
else if (!offthescreen)
{ if (ang!=0) SetWorldTransform(hdc,&mat);
if (bmp.hbmask!=0)
{ if (holdt==0) holdt=SelectObject(tdc,bmp.hbmask); else SelectObject(tdc,bmp.hbmask);
if (WhitePrint)
{ SelectObject(hdc,GetStockObject(LTGRAY_BRUSH));
StretchBlt(hdc,x0,y0,x1-x0,y1-y0,tdc,0,0,bmp.bwidth,bmp.bheight,0x00A803A9);
// that's a ternary op: (brush OR mask) AND hdc -- because mask uses 255 for,
// the mask area, and 0 for the solid, we OR it to get 128 for the solid area.
}
else StretchBlt(hdc,x0,y0,x1-x0,y1-y0,tdc,0,0,bmp.bwidth,bmp.bheight,SRCAND);
}
if (bmp.hbm!=0 && !WhitePrint)
{ if (holdt==0) holdt=SelectObject(tdc,bmp.hbm); else SelectObject(tdc,bmp.hbm);
if (bmp.hbmask!=0) StretchBlt(hdc,x0,y0,x1-x0,y1-y0,tdc,0,0,bmp.bwidth,bmp.bheight,SRCPAINT);
else StretchBlt(hdc,x0,y0,x1-x0,y1-y0,tdc,0,0,bmp.bwidth,bmp.bheight,SRCCOPY);
}
mat.eM11=1; mat.eM12=0; mat.eM21=0; mat.eM22=1; mat.eDx=0; mat.eDy=0;
if (ang!=0) SetWorldTransform(hdc,&mat);
}
}
if (simplecircle)
{ TLimb &limb = body->limbs[shape.p[0].i];
double dx=limb.x-limb.x0,dy=limb.y-limb.y0, rad=sqrt(dx*dx+dy*dy);
int x0=b2x(limb.x0-rad), y0=b2y(limb.y0-rad), x1=b2x(limb.x0+rad), y1=b2y(limb.y0+rad);
HPEN hspen=CreatePen(PS_NULL,0,0); HGDIOBJ hop=SelectObject(hdc,hspen);
if (shape.line.dtype==ctNone) {}
else if (shape.line.dtype==ctRGB)
{ lpen.set(shape.thickness,heavy,true,shape.line.rgb.r,shape.line.rgb.g,shape.line.rgb.b);
SelectObject(hdc,lpen.hpen);
}
else {fail=true; if (err!=0) *err="shape line colour";}
LOGBRUSH lbr;
if (shape.brush.dtype==ctNone || shape.brush.dtype==ctBitmap) lbr.lbStyle=BS_NULL;
else if (shape.brush.dtype==ctRGB) {lbr.lbStyle=BS_SOLID; lbr.lbColor=RGB(shape.brush.rgb.r,shape.brush.rgb.g,shape.brush.rgb.b);}
else if (shape.brush.dtype==ctDefault) {lbr.lbStyle=BS_SOLID; lbr.lbColor=vert?RGB(0,0,0):RGB(255,255,255);}
else {fail=true; if (err!=0) *err="shape brush colour";}
HBRUSH hsbr=CreateBrushIndirect(&lbr); HGDIOBJ hob = SelectObject(hdc,hsbr);
Ellipse(hdc,x0,y0,x1,y1);
SelectObject(hdc,hob); DeleteObject(hsbr);
SelectObject(hdc,hop); DeleteObject(hspen);
}
else
{ // not a simple circle, so we do it the long way...,
// first, build the pt[] array.
int ptpos=0; for (int si=0; si<(int)shape.p.size(); si++)
{ TJointRef j0=shape.p[si], j1=shape.p[(si+1)%shape.p.size()];
TLimb &limb0=body->limbs[j0.i]; //, &limb1=body->limbs[j1.i];
if (j0.i==j1.i && j0.ar!=j1.ar && (limb0.type==1 || limb0.type==3)) ptpos=add_arc(gb2x,gb2y,this,&ept,ptpos,limb0,j0.ar,-1);
else ptpos=add_pt(gb2x,gb2y,this,&ept,ptpos,limb0,j0.ar,-1);
}
if (shape.p.size()>2) ptpos=ept.add(ptpos,ept.pt[0].x,ept.pt[0].y,shape.p.size()-1); // to close it!
if (shape.brush.dtype==ctRGB || shape.brush.dtype==ctDefault)
{ HPEN hspen=CreatePen(PS_NULL,0,0); HGDIOBJ hop = SelectObject(hdc,hspen);
LOGBRUSH lbr; lbr.lbStyle=BS_SOLID;
lbr.lbColor=RGB(shape.brush.rgb.r,shape.brush.rgb.g,shape.brush.rgb.b); if (shape.brush.dtype==ctDefault) lbr.lbColor=vert?RGB(0,0,0):RGB(255,255,255);
HBRUSH hsbr=CreateBrushIndirect(&lbr); HGDIOBJ hob = SelectObject(hdc,hsbr);
Polygon(hdc,ept.pt,ptpos);
SelectObject(hdc,hob); DeleteObject(hsbr);
SelectObject(hdc,hop); DeleteObject(hspen);
}
double tt = shape.thickness;
lpen.set(tt,heavy,shape.line.dtype==ctRGB,shape.line.rgb.r,shape.line.rgb.g,shape.line.rgb.b);
SelectObject(hdc,lpen.hpen);
Polyline(hdc,ept.pt,ptpos);
}
}
// now draw the actual lines
if (shape.limbs)
{ int tot=body->nlimbs; if (mode==mCreateDragging) tot++;
for (n=1; n<tot; n++)
{ TLimb *limb; if (n<body->nlimbs) limb=&body->limbs[n]; else limb=&rubber;
bool heavy=false;
if (n==body->nlimbs) heavy=true; // for the pretend line that is our create-drag
if (mode!=mCreateDragging)
{ for (list<int>::const_iterator si=sellimbs.begin(); si!=sellimbs.end(); si++) {if (n==*si) heavy=true;}
}
bool changed = lpen.set(limb->thickness,heavy,limb->color.dtype==ctRGB,limb->color.rgb.r,limb->color.rgb.g,limb->color.rgb.b);
if (changed||n==1) SelectObject(hdc,lpen.hpen);
bool isarc = (limb->type==1 || limb->type==3 || (limb==&rubber && rubber.root==rubend.i && rubend.ar));
if (!isarc) // a line or spring
{ MoveToEx(hdc,b2x(limb->x0),b2y(limb->y0),NULL); LineTo(hdc,b2x(limb->x),b2y(limb->y));
}
else // an arc.
{ bool isrubarc = (limb==&rubber && rubber.root==rubend.i && rubend.ar);
// rubarc: origin at rubber->root->x0y0, radius=rubber->root->length, ends at rubber->root->ang0,1
// normarc: origin at limb->x0y0, radius=limb->length, ends=limb->ang0,1
TLimb *arclimb=limb;
if (isrubarc) arclimb=&body->limbs[limb->root];
double d=arclimb->length;
double angA,angB;
if (arclimb->type==3) {angA=arclimb->ang; angB=angA-1.96*pi; double dx=arclimb->x-arclimb->x0,dy=arclimb->y-arclimb->y0; d=sqrt(dx*dx+dy*dy);}
else if (arclimb->ascale<0) {angA=arclimb->ang0;angB=arclimb->ang;}
else {angA=arclimb->ang; angB=arclimb->ang0;}
int xA=b2x(arclimb->x0+d*cos(angA)), yA=b2y(arclimb->y0+d*sin(angA));
int xB=b2x(arclimb->x0+d*cos(angB)), yB=b2y(arclimb->y0+d*sin(angB));
int ddAB=(xB-xA)*(xB-xA)+(yB-yA)*(yB-yA);
bool suppresscircle=false;
if (limb->type==3 && limb!=&rubber && limb->color.dtype!=ctNone)
{ int ci=circleshape_from_limb(n); if (ci!=-1 && body->shapes[ci].line.dtype!=ctNone) suppresscircle=true;
}
if (!suppresscircle)
{ if (ddAB<100 && angA-angB<pi) {MoveToEx(hdc,xA,yA,NULL); LineTo(hdc,xB,yB);}
else Arc(hdc,b2x(arclimb->x0-d),b2y(arclimb->y0-d),b2x(arclimb->x0+d),b2y(arclimb->y0+d), xA,yA, xB,yB);
}
}
}
}
}
//
// Draw all the joints. We count how this joint is used: 0=all offset, 1=mixed, 2=all fixed
vector<int> numoff,numfix,use;
numoff.resize(body->nlimbs); numfix.resize(body->nlimbs); use.resize(body->nlimbs);
for (n=0; n<body->nlimbs; n++) {numoff[n]=0; numfix[n]=0;}
for (n=0; n<body->nlimbs; n++) {int r=body->limbs[n].root; if (body->limbs[n].aisoff) numoff[r]++; else numfix[r]++;}
for (n=0; n<body->nlimbs; n++) {if (numfix[n]==0) use[n]=0; else if (numoff[n]==0) use[n]=2; else use[n]=1;}
SelectObject(hdc,GetStockObject(vert?WHITE_PEN:BLACK_PEN));
SelectObject(hdc,GetStockObject(vert?BLACK_BRUSH:WHITE_BRUSH));
if (ShowJoints)
{ for (n=0; n<body->nlimbs; n++)
{ TLimb &limb=body->limbs[n]; int x0=b2x(limb.x), y0=b2y(limb.y);
if (use[n]<2) Ellipse(hdc,x0-SpotLength,y0-SpotLength,x0+SpotLength,y0+SpotLength);
if (use[n]==1) Rectangle(hdc,x0-SpotLength,y0-SpotLength,x0,y0+SpotLength);
if (use[n]==2) Rectangle(hdc,x0-SpotLength,y0-SpotLength,x0+SpotLength,y0+SpotLength);
}
}
else
{ for (list<int>::const_iterator i=sellimbs.begin(); i!=sellimbs.end(); i++)
{ TLimb &limb=body->limbs[*i]; int x0=b2x(limb.x), y0=b2y(limb.y);
if (use[n]<2) Ellipse(hdc,x0-SpotLength,y0-SpotLength,x0+SpotLength,y0+SpotLength);
if (use[n]==1) Rectangle(hdc,x0-SpotLength,y0-SpotLength,x0,y0+SpotLength);
if (use[n]==2) Rectangle(hdc,x0-SpotLength,y0-SpotLength,x0+SpotLength,y0+SpotLength);
}
}
//
// corner-creating nodules for while we're in the middle of dragging a vertex
if (cori!=-1)
{ stk::TShape &shape = body->shapes[hit.s];
// we now draw the orange lines from i0 to corx,cory to i2.
// if corx,cory are actually a cortarget, then the orange lines might conceivably be points
int i0=cori, i2=(cori+1)%shape.p.size();
TJointRef j0=shape.p[i0], j1=cortarget, j2=shape.p[i2];
int ptpos=0;
if (j0.i==cortarget.i && j0.ar!=cortarget.ar) ptpos=add_arc(gb2x,gb2y,this,&ept,ptpos,body->limbs[j0.i],j0.ar,-1);
else ptpos=add_pt(gb2x,gb2y,this,&ept,ptpos,body->limbs[j0.i],j0.ar,-1);
if (j2.i==cortarget.i && j2.ar!=cortarget.ar) ptpos=add_arc(gb2x,gb2y,this,&ept,ptpos,body->limbs[j2.i],!j2.ar,-1);
else ptpos=add_pt(gb2x,gb2y,this,&ept,ptpos,corx,cory,-1);
ptpos=add_pt(gb2x,gb2y,this,&ept,ptpos,body->limbs[j2.i],j2.ar,-1);
lpen.set(2,false,true,255,128,0); SelectObject(hdc,lpen.hpen);
Polyline(hdc,ept.pt,ptpos);
}
// shape handles on the currently selected shapes
for (list<int>::const_iterator si=selshapes.begin(); si!=selshapes.end(); si++)
{ stk::TShape &shape = body->shapes[*si];
bool simplecircle = (shape.p.size()==2 && shape.p[0].i==shape.p[1].i && body->limbs[shape.p[0].i].type==3);
SelectObject(hdc,hAnglePen);
SelectObject(hdc,GetStockObject(BLACK_BRUSH));
int avx=0, avy=0, avn=(int)shape.p.size();
for (int li=0; li<(int)shape.p.size(); li++)
{ TJointRef j = shape.p[li];
TLimb &limb = body->limbs[j.i]; bool ar=j.ar;
double xx,yy; jointpos(&xx,&yy,limb,ar);
int x=b2x(xx), y=b2y(yy);
if (!simplecircle) Rectangle(hdc,x-ArmSpotLength,y-ArmSpotLength,x+ArmSpotLength,y+ArmSpotLength);
avx+=x; avy+=y;
}
avx/=avn; avy/=avn;
{ // a circle
TLimb &limb = body->limbs[shape.p[0].i];
avx = b2x(0.3*limb.x0 + 0.7*limb.x);
avy = b2y(0.3*limb.y0 + 0.7*limb.y);
}
Rectangle(hdc,avx-ArmSpotLength,avy-ArmSpotLength,avx+ArmSpotLength,avy+ArmSpotLength);
}
// handles for selection
for (list<TLimb*>::const_iterator si=sels.begin(); si!=sels.end(); si++)
{ TLimb *sel=*si;
// angle handles
if (sel->type==0 || sel->type==1)
{ SelectObject(hdc,hAnglePen);
SelectObject(hdc,hAngleBrush);
double d=ArmLength;
int x0=b2x(sel->x0)+(int)(d*cos(sel->ang0)), y0=b2y(sel->y0)+(int)(d*sin(sel->ang0));
int x1=b2x(sel->x0)+(int)(d*cos(sel->ang1)), y1=b2y(sel->y0)+(int)(d*sin(sel->ang1));
if (sel->chan==4 && sel->band==1) {fail=true; if (err!=0) *err="I thought I got rid of freq 4.1";}
bool showmin=(sel->chan!=4 || sel->band!=0), showmax=showmin;
if (sel->type==1) showmin=true;
if (showmin)
{ SelectObject(hdc,GetStockObject(BLACK_BRUSH));
MoveToEx(hdc,b2x(sel->x0),b2y(sel->y0),NULL); LineTo(hdc,x0,y0); Rectangle(hdc,x0-ArmSpotLength,y0-ArmSpotLength,x0+ArmSpotLength,y0+ArmSpotLength);
}
if (showmax)
{ SelectObject(hdc,GetStockObject(GRAY_BRUSH));
MoveToEx(hdc,b2x(sel->x0),b2y(sel->y0),NULL); LineTo(hdc,x1,y1); Rectangle(hdc,x1-ArmSpotLength,y1-ArmSpotLength,x1+ArmSpotLength,y1+ArmSpotLength);
}
}
// spring handles
if (sel->type==2 || sel->type==3)
{ SelectObject(hdc,hAnglePen);
double d=ArmLength;
double ddx=cos(sel->ang+0.5*pi)*d/2, ddy=sin(sel->ang+0.5*pi)*d/2;
int dx=(int)ddx, dy=(int)ddy;
//double lf=sel->lmin*(1-sel->f)+sel->length*sel->f;
int x,y, x0,y0,x1,y1;
if (sel->chan==4 && sel->band==1) {fail=true; if (err!=0) *err="I thought I got rid of freq 4.1";}
bool showmin=(sel->chan!=4 || sel->band!=0), showmax=showmin;
if (showmax)
{ x=b2x(sel->x0+sel->lmin*cos(sel->ang)); y=b2y(sel->y0+sel->lmin*sin(sel->ang));
x0=x+dx; y0=y+dy; x1=x-dx; y1=y-dy;
SelectObject(hdc,GetStockObject(GRAY_BRUSH));
MoveToEx(hdc,x0,y0,NULL); LineTo(hdc,x1,y1); Rectangle(hdc,x1-ArmSpotLength,y1-ArmSpotLength,x1+ArmSpotLength,y1+ArmSpotLength);
}
if (showmin)
{ x=b2x(sel->x0+sel->length*cos(sel->ang)); y=b2y(sel->y0+sel->length*sin(sel->ang));
x0=x+dx; y0=y+dy; x1=x-dx; y1=y-dy;
SelectObject(hdc,GetStockObject(BLACK_BRUSH));
MoveToEx(hdc,x0,y0,NULL); LineTo(hdc,x1,y1); Rectangle(hdc,x1-ArmSpotLength,y1-ArmSpotLength,x1+ArmSpotLength,y1+ArmSpotLength);
}
}
}
// rubber-band zooming
if (mode==mZoomDragging || mode==mSelDragging)
{ SelectObject(hdc,GetStockObject(NULL_BRUSH));
SelectObject(hdc,hRubberPen);
Rectangle(hdc,zoomx0,zoomy0,zoomx,zoomy);
}
//
SelectObject(hdc,holdb);
SelectObject(hdc,holdp);
DeleteObject(hAnglePen);
DeleteObject(hPlusPen);
DeleteObject(hAngleBrush);
DeleteObject(hRubberPen);
DeleteObject(hAnchorPen);
DeleteObject(hBorderPen);
if (holdt!=0) SelectObject(tdc,holdt); DeleteDC(tdc);
//
BitBlt(hwndc,0,0,width,height,hdc,0,0,SRCCOPY);
//
return !fail;
}
int WINAPI AboutDlgProc(HWND hdlg,UINT msg,WPARAM,LPARAM)
{ switch (msg)
{ case WM_INITDIALOG:
{ // 1. the VersionInfo resource
string vi="???";
DWORD hVersion; char fn[MAX_PATH]; GetModuleFileName(hInstance,fn,MAX_PATH);
DWORD vis=GetFileVersionInfoSize(fn,&hVersion);
if (vis!=0)
{ char *vData = new char[(UINT)vis];
if (GetFileVersionInfo(fn,hVersion,vis,vData))
{ char vn[100];
strcpy(vn,"\\VarFileInfo\\Translation");
LPVOID transblock; UINT vsize;
BOOL res=VerQueryValue(vData,vn,&transblock,&vsize);
if (res)
{ DWORD ot = *(DWORD*)transblock, lo=(HIWORD(ot))&0xffff, hi=((LOWORD(ot))&0xffff)<<16;
*(DWORD *)transblock = lo|hi;
wsprintf(vn,"\\StringFileInfo\\%08lx\\%s",*(DWORD *)transblock,"FileVersion");
char *ver;
res=VerQueryValue(vData,vn,(LPVOID*)&ver,&vsize);
if (res)
{ char c[100]; char *d=c;
while (*ver!=0)
{ if (*ver==',') {*d='.'; d++; ver++;}
else if (*ver==' ') {*ver++;}
else {*d=*ver; d++; ver++;}
}
*d=0; vi=string(c);
}
}
}
delete[] vData;
}
// 2. the body's version number
string bv="???";
TBody *b = new TBody();
bv = b->version;
delete b;
// 3. the version written in the manifest
string mv="???";
HRSRC hrsrc = FindResource(hInstance,MAKEINTRESOURCE(1),MAKEINTRESOURCE(24)); // 24 is RT_MANIFEST
if (hrsrc!=NULL)
{ HANDLE hglob = LoadResource(hInstance,hrsrc);
DWORD size = SizeofResource(hInstance,hrsrc);
if (hglob!=NULL)
{ char *dat = (char*)LockResource(hglob);
char *nd = new char[size]; memcpy(nd,dat,size); nd[size-1]=0;
// we assume that the first assembly mentioned in the file is the file itself
char *assemstart = strstr(nd,"<assemblyIdentity");
char *assemend=0; if (assemstart!=0) assemend = strstr(assemstart,"/>");
if (assemstart!=0 && assemend!=0)
{ *assemend=0;
char *verstart = strstr(assemstart,"version=");
char *verend=0; if (verstart!=0) verend = strstr(verstart,"\n");
if (verstart!=0 && verend!=0)
{ verstart=verstart+8; *verend=0;
if (*verstart=='"') verstart++;
verend--; if (*verend=='\r') verend--; if (*verend=='"') verend--;
verend++;
mv=string(verstart,verend-verstart);
}
}
}
}
string msg = "version "+vi+" (core "+bv+" manifest "+mv+")";
SetDlgItemText(hdlg,ID_VERSION,msg.c_str());
//
void SetDlgItemUrl(HWND hdlg,int id,const char *url) ;
SetDlgItemUrl(hdlg,ID_HREF,"http://www.wischik.com/lu/senses/sticky");
return TRUE;
}
case WM_COMMAND: EndDialog(hdlg,IDOK); return TRUE;
}
return FALSE;
}
//LRESULT CALLBACK DebugWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
//{ TEditor *editor;
// #pragma warning( push ) // my code is clean! but the compiler won't believe me...
// #pragma warning( disable : 4244 4312 )
// if (msg==WM_CREATE)
// { CREATESTRUCT *cs=(CREATESTRUCT*)lParam;
// editor=(TEditor*)cs->lpCreateParams;
// SetWindowLongPtr(hwnd,GWLP_USERDATA,(LONG_PTR)editor);
// }
// else
// { editor=(TEditor*)GetWindowLongPtr(hwnd,GWLP_USERDATA);
// }
// #pragma warning( pop )
// switch (msg)
// { case WM_PAINT:
// { PAINTSTRUCT ps; BeginPaint(hwnd,&ps);
// RECT rc; GetClientRect(hwnd,&rc);
// editor->DebugPaint(ps.hdc,rc);
// EndPaint(hwnd,&ps);
// } break;
// }
// return DefWindowProc(hwnd,msg,wParam,lParam);
//}
//HWND CreateDebugWindow(TEditor *editor)
//{ WNDCLASSEX wcex; ZeroMemory(&wcex,sizeof(wcex)); wcex.cbSize = sizeof(WNDCLASSEX);
// BOOL res=GetClassInfoEx(hInstance,"Stick3DebugClass",&wcex);
// if (!res)
// { wcex.style = CS_HREDRAW | CS_VREDRAW;
// wcex.lpfnWndProc = (WNDPROC)DebugWndProc;
// wcex.cbClsExtra = 0;
// wcex.cbWndExtra = 0;
// wcex.hInstance = hInstance;
// wcex.hIcon = LoadIcon(NULL,MAKEINTRESOURCE(1));
// wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
// wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
// wcex.lpszMenuName = NULL;
// wcex.lpszClassName = "Stick3DebugClass";
// wcex.hIconSm = NULL;
// ATOM res=RegisterClassEx(&wcex);
// if (res==0) {MessageBox(NULL,"Failed to register class","Error",MB_OK); return 0;}
// }
// //
// HWND hwnd = CreateWindowEx(0,"Stick3DebugClass", "Sticky Debug",
// WS_POPUP,
// 900, 100, 124, 400, NULL, NULL, hInstance, editor);
// if (hwnd==NULL) {MessageBox(NULL,"Failed to create window","Error",MB_OK); return 0;}
// ShowWindow(hwnd,SW_SHOW);
// return hwnd;
//}
LRESULT CALLBACK ClientWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ TEditor *editor;
#pragma warning( push ) // my code is clean! but the compiler won't believe me...
#pragma warning( disable : 4244 4312 )
if (msg==WM_CREATE) {CREATESTRUCT *cs=(CREATESTRUCT*)lParam; editor=(TEditor*)cs->lpCreateParams; SetWindowLongPtr(hwnd,GWLP_USERDATA,(LONG_PTR)editor);}
else {editor=(TEditor*)GetWindowLongPtr(hwnd,GWLP_USERDATA);}
#pragma warning( pop )
if (editor==NULL) return DefWindowProc(hwnd,msg,wParam,lParam);
switch (msg)
{ case WM_PAINT:
{ PAINTSTRUCT ps; HDC hdc=BeginPaint(hwnd, &ps);
string err; bool ok=editor->Draw(hdc,&err);
EndPaint(hwnd, &ps);
if (!ok) editor->ShowHint(err);
return 0;
}
case WM_ERASEBKGND: return 1;
case WM_HSCROLL: editor->Scroll(true,LOWORD(wParam),HIWORD(wParam)); break;
case WM_VSCROLL: editor->Scroll(false,LOWORD(wParam),HIWORD(wParam)); break;
case WM_RBUTTONDOWN:
{ if (editor->mode==mNothing) editor->RightClick(LOWORD(lParam),HIWORD(lParam));
else if (editor->mode==mNothingTesting) editor->StopAnimate();
break;
}
case WM_LBUTTONDOWN:
{ if (editor->mode==mNothing) editor->ButtonDown(LOWORD(lParam),HIWORD(lParam));
else if (editor->mode==mNothingTesting) editor->StopAnimate();
break;
}
case WM_MOUSEMOVE:
{ int x=LOWORD(lParam), y=HIWORD(lParam);
if (editor->mode==mNothing) editor->HoverMonitor(x,y);
else if (editor->mode==mNodePressing) editor->SelectWobble(x,y);
else if (editor->mode==mShapeLinePressing) editor->SelectShapeLineWobble(x,y);
else if (editor->mode==mShapeSpotPressing) editor->SelectShapeSpotWobble(x,y);
else if (editor->mode==mCreateDragging) editor->CreatingMove(x,y);
else if (editor->mode==mCreateCornerDragging) editor->CornerMove(x,y);
else if (editor->mode==mCornerMoving) editor->CornerMove(x,y);
else if (editor->mode==mNodeMoving) editor->RepositioningMove(editor->hit.n,x,y);
else if (editor->mode==mAoffDragging) editor->AngleMove(x,y);
else if (editor->mode==mAscaleDragging) editor->AngleMove(x,y);
else if (editor->mode==mLminDragging) editor->SpringMove(x,y);
else if (editor->mode==mLmaxDragging) editor->SpringMove(x,y);
else if (editor->mode==mZoomDragging) editor->RubberMove(x,y);
else if (editor->mode==mSelDragging) editor->RubberMove(x,y);
break;
}
case WM_LBUTTONUP:
{ if (editor->mode==mNodePressing) editor->Unselect();
else if (editor->mode==mShapeLinePressing) editor->Unselect();
else if (editor->mode==mShapeSpotPressing) editor->Unselect();
else if (editor->mode==mCreateDragging) editor->FinishCreate();
else if (editor->mode==mCreateCornerDragging) editor->FinishCreateCorner();
else if (editor->mode==mCornerMoving) editor->FinishCreateCorner();
else if (editor->mode==mNodeMoving) editor->FinishRepositioning();
else if (editor->mode==mAoffDragging) editor->FinishAngling();
else if (editor->mode==mAscaleDragging) editor->FinishAngling();
else if (editor->mode==mLminDragging) editor->FinishSpringing();
else if (editor->mode==mLmaxDragging) editor->FinishSpringing();
else if (editor->mode==mZoomDragging) editor->FinishZooming();
else if (editor->mode==mSelDragging) editor->FinishSeling();
break;
}
case WM_SIZE:
{ editor->Size(LOWORD(lParam),HIWORD(lParam));
break;
}
case WM_SETCURSOR:
{ if (LOWORD(lParam)==HTCLIENT) {editor->SetCursor(); return 0;}
break;
}
}
return DefWindowProc(hwnd,msg,wParam,lParam);
}
LRESULT CALLBACK EditWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{ TEditor *editor;
#pragma warning( push ) // my code is clean! but the compiler won't believe me...
#pragma warning( disable : 4244 4312 )
if (msg==WM_CREATE) {CREATESTRUCT *cs=(CREATESTRUCT*)lParam; editor=(TEditor*)cs->lpCreateParams; SetWindowLongPtr(hwnd,GWLP_USERDATA,(LONG_PTR)editor);}
else {editor=(TEditor*)GetWindowLongPtr(hwnd,GWLP_USERDATA);}
#pragma warning( pop )
switch (msg)
{ case WM_CREATE:
{ //hdb = CreateDebugWindow(editor);
return 0;
}
case WM_DESTROY:
{ PostQuitMessage(0);
return 0;
}
case WM_TIMER:
{ if (editor->mode==mNothingTesting) editor->Tick(false);
break;
}
case WM_COMMAND:
{ int id=LOWORD(wParam); //code=HIWORD(wParam)
if (editor->mode==mNothing && id==ID_FILE_NEW) editor->FileNew();
else if (editor->mode==mNothing && id==ID_FILE_OPEN) editor->FileOpen("");
else if (editor->mode==mNothing && id==ID_FILE_SAVE) editor->FileSave();
else if (editor->mode==mNothing && id==ID_FILE_SAVEAS) editor->FileSaveAs(editor->curfile);
else if (editor->mode==mNothing && id==ID_FILE_EXPORTAVI) editor->FileExport();
else if (editor->mode==mExporting && id==ID_FILE_EXPORTAVI) editor->ExportCancelled=true;
else if (editor->mode==mExporting && id==ID_EXPORTCANCEL) editor->ExportCancelled=true;
else if (id==ID_FILE_EXIT) SendMessage(hwnd,WM_CLOSE,0,0);
else if (editor->mode==mNothing && id==ID_EDIT_INSERT && editor->mode==mNothing && editor->sellimbs.size()==1) editor->InsertLimb();
else if (editor->mode==mNothing && id==ID_EDIT_DELETE && editor->mode==mNothing) editor->DeleteLimbOrShape();
else if (editor->mode==mNothing && id==ID_EDIT_CUT && editor->mode==mNothing) editor->Cut();
else if (editor->mode==mNothing && id==ID_EDIT_COPY && editor->mode==mNothing) editor->Copy();
else if (editor->mode==mNothing && id==ID_EDIT_PASTE && editor->mode==mNothing) editor->Paste();
else if (editor->mode==mNothing && id==ID_EDIT_FLIP) editor->Flip();
else if (editor->mode==mNothing && id==ID_EDIT_ENLARGE) editor->Stretch(1);
else if (editor->mode==mNothing && id==ID_EDIT_SHRINK) editor->Stretch(-1);
else if (editor->mode==mNothing && id==ID_EDIT_UNDO) editor->EditUndo();
else if (editor->mode==mNothing && id==ID_EDIT_REDO) editor->EditRedo();
else if (editor->mode==mNothing && id==ID_EDIT_MARK) editor->MarkUndo();
else if (editor->mode==mNothing && id==ID_CDOWN) editor->Cursor(3);
else if (editor->mode==mNothing && id==ID_CLEFT) editor->Cursor(0);
else if (editor->mode==mNothing && id==ID_CUP) editor->Cursor(1);
else if (editor->mode==mNothing && id==ID_CRIGHT) editor->Cursor(2);
else if ((editor->mode==mNothing || editor->mode==mNothingTesting) && id==ID_TOOLS_TEST) {if (editor->mode==mNothingTesting) editor->StopAnimate(); else editor->Animate();}
else if (id==ID_TOOLS_SHOWANGLES) {ShowAngles=!ShowAngles; RegSaveUser(); editor->UpdateMenus(); editor->Redraw();}
else if (id==ID_TOOLS_SHOWJOINTS) {ShowJoints=!ShowJoints; RegSaveUser(); editor->UpdateMenus(); editor->Redraw();}
else if (id==ID_TOOLS_SHOWINVISIBLES) {ShowInvisibles=!ShowInvisibles; RegSaveUser(); editor->UpdateMenus(); editor->Redraw();}
else if (id==ID_TOOLS_SHOW) {bool olds=(ShowAngles|ShowJoints|ShowInvisibles), news=!olds; ShowAngles=news; ShowJoints=news; ShowInvisibles=news; RegSaveUser(); editor->UpdateMenus(); editor->Redraw();}
else if (editor->mode==mNothing && id==ID_TOOLS_ZOOMMODE) {editor->tool=tZoom; editor->ShowHint("");}
else if (editor->mode==mNothing && id==ID_TOOLS_EDITMODE) {editor->tool=tEdit; editor->ShowHint("");}
else if (editor->mode==mNothing && id==ID_TOOLS_CREATEMODE) {editor->tool=tCreate; editor->ShowHint("");}
else if (editor->mode==mNothing && id==ID_TOOLS_HITTEST) {editor->ShowHitTest();}
else if (editor->mode==mNothing && id==ID_TOOLS_USERCOLOURS) editor->UserColours(editor->mhwnd);
else if (editor->mode==mNothing && id==ID_TOOLS_USERCUMULATIVES) editor->UserCumulatives(editor->mhwnd);
else if (editor->mode==mNothing && id==ID_TOOLS_USERTHICKNESS) editor->UserThicknesses(editor->mhwnd);
else if (editor->mode==mNothing && id==ID_TOOLS_BITMAPS) editor->Bitmaps(editor->mhwnd);
else if (editor->mode==mNothing && id==ID_TOOLS_SNAP) {UserSnap=!UserSnap; RegSaveUser(); editor->UpdateMenus();}
else if (editor->mode==mNothing && id==ID_TOOLS_GRID) {UserGrid=!UserGrid; RegSaveUser(); editor->UpdateMenus(); editor->Redraw();}
else if (editor->mode==mNothing && id==ID_TOOLS_BACKDROP) {if (editor->hbackdrop==0) editor->Backdrop("?"); else editor->Backdrop("");}
else if (editor->mode==mNothing && id==ID_TOOLS_CHECKUPRIGHT) editor->MaybeCheckUpright(true);
else if (editor->mode==mNothing && id==ID_TOOLS_STYLES) editor->Styles(editor->mhwnd);
else if (editor->mode==mNothing && id==ID_TOOLS_EFFECTS) editor->Effects(editor->mhwnd);
else if (editor->mode==mNothing && id==ID_TOOLS_CATEGORY) editor->Category();
else if (editor->mode==mNothing && id==ID_TOOLS_TARGETFRAMERATE) editor->TargetFramerate();
else if (id==ID_INVERT) editor->Invert();
else if (editor->mode==mNothing && id==ID_HELP_ABOUT) {DialogBox(hInstance,MAKEINTRESOURCE(IDD_ABOUT),hwnd,AboutDlgProc);}
else if (editor->mode==mNothing && id==ID_HELP_HELP)
{ string hlp = GetStickDir(true)+"\\sticky.txt";
ShellExecute(hwnd,"open",hlp.c_str(),NULL,NULL,SW_SHOWNORMAL);
}
else if (id==ID_ZOOMIN) editor->Zoom(1);
else if (id==ID_ZOOMOUT) editor->Zoom(-1);
else if (id==ID_ZOOMFULL) editor->Zoom(0);
else if (editor->mode==mNothing && id>=ID_STYLEA && id<=ID_STYLET) editor->SetStyle((char)(id+'A'-ID_STYLEA));
else if (editor->mode==mNothing && id==ID_FIXED) editor->SetChanBand(4,0);
else if (editor->mode==mNothing && id==ID_LEFT) editor->SetChanBand(0,-1);
else if (editor->mode==mNothing && id==ID_RIGHT) editor->SetChanBand(1,-1);
else if (editor->mode==mNothing && id==ID_DIFFERENCE) editor->SetChanBand(2,-1);
else if (editor->mode==mNothing && id==ID_1) editor->SetChanBand(-1,0);
else if (editor->mode==mNothing && id==ID_2) editor->SetChanBand(-1,1);
else if (editor->mode==mNothing && id==ID_3) editor->SetChanBand(-1,2);
else if (editor->mode==mNothing && id==ID_4) editor->SetChanBand(-1,3);
else if (editor->mode==mNothing && id==ID_5) editor->SetChanBand(-1,4);
else if (editor->mode==mNothing && id==ID_6) editor->SetChanBand(-1,5);
else if (editor->mode==mNothing && id==ID_NEGATIVE) editor->ToggleNegative();
else if (editor->mode==mNothing && id==ID_LINETYPE) editor->ToggleLineType();
else if (editor->mode==mNothing && id==ID_VISIBILITY) editor->SetVisibility(tsWhatever,-1);
else if (editor->mode==mNothing && id==ID_RED) editor->SetCol(tsWhatever,cRed);
else if (editor->mode==mNothing && id==ID_GREEN) editor->SetCol(tsWhatever,cGreen);
else if (editor->mode==mNothing && id==ID_BLUE) editor->SetCol(tsWhatever,cBlue);
else if (editor->mode==mNothing && id==ID_YELLOW) editor->SetCol(tsWhatever,cYellow);
else if (editor->mode==mNothing && id==ID_BLACK) editor->SetCol(tsWhatever,cBlack);
else if (editor->mode==mNothing && id==ID_PURPLE) editor->SetCol(tsWhatever,cPurple);
else if (editor->mode==mNothing && id==ID_WHITE) editor->SetCol(tsWhatever,cWhite);
else if (editor->mode==mNothing && id==ID_THIN) editor->SetThickness(0);
else if (editor->mode==mNothing && id==ID_MEDIUM) editor->SetThickness(1);
else if (editor->mode==mNothing && id==ID_HEAVY) editor->SetThickness(2);
else if (editor->mode==mNothing && id==ID_TOFRONT) editor->SetOrder(2);
else if (editor->mode==mNothing && id==ID_TOBACK) editor->SetOrder(-2);
else if (editor->mode==mNothing && editor->hit.n>0 && id==ID_0)
{ TLimb &limb=editor->body->limbs[editor->hit.n];
if (limb.chan==0 || limb.chan==1 || limb.chan==3) editor->SetF(0,limb.chan,limb.band,0);
}
//
editor->UpdateMenus(); editor->SetCursor();
break;
}
case WM_CLOSE:
{ if (editor->mode==mExporting) {editor->ExportCancelled=true; editor->ExportTerminated=true; return 0;}
else
{ bool res=editor->FileClose();
if (!res) return 0;
}
break;
}
case WM_SIZE:
{ int width=LOWORD(lParam), height=HIWORD(lParam);
SendMessage(editor->hstatwnd,WM_SIZE,0,lParam);
RECT rc; GetWindowRect(editor->hstatwnd,&rc); int sheight=rc.bottom-rc.top;
MoveWindow(editor->chwnd,0,0,width,height-sheight,TRUE);
break;
}
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void RegLoadUser()
{ usercols.clear(); userthick.clear(); usercums.clear(); exportfn="";
UserSnap=true; UserGrid=false; WhitePrint=false; UserBmpBackground=RGB(128,128,128);
ShowAngles=true; ShowJoints=true; ShowInvisibles=true;
UserCheckUpright=true;
exportfn=""; exportproc=false; exportfigs=""; exporttune=1; exportw=128; exporth=128;
exporttimefixed=true; exporttime=10000; exportfps=20; exportcompress=true; exportopt=0; exportproctime=4000;
UserBacks.clear();
HKEY key=NULL; char dat[10000]; DWORD ddat; DWORD size; DWORD type;
LONG res=RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Lu\\Sticky",0,KEY_READ,&key);
if (res==ERROR_SUCCESS)
{ size=sizeof(dat); *dat=0; res=RegQueryValueEx(key,"userbacks",NULL,&type,(LPBYTE)&dat,&size); if (res==ERROR_SUCCESS) ParseUserBacks(dat);
size=sizeof(dat); *dat=0; res=RegQueryValueEx(key,"usercols",NULL,&type,(LPBYTE)&dat,&size); if (res==ERROR_SUCCESS) ParseUserCols(dat);
size=sizeof(dat); *dat=0; res=RegQueryValueEx(key,"usercums",NULL,&type,(LPBYTE)&dat,&size); ParseUserCums(dat);
size=sizeof(dat); *dat=0; res=RegQueryValueEx(key,"userthick",NULL,&type,(LPBYTE)&dat,&size); if (res==ERROR_SUCCESS) ParseUserThicks(dat);
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"usersnap",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) UserSnap = (ddat!=0);
size=sizeof(ddat); ddat=0; res=RegQueryValueEx(key,"usergrid",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) UserGrid = (ddat!=0);
size=sizeof(ddat); ddat=0; res=RegQueryValueEx(key,"uservert",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) WhitePrint = (ddat!=0);
size=sizeof(ddat); ddat=128; res=RegQueryValueEx(key,"previewbmpbackground",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) UserBmpBackground=RGB(ddat,ddat,ddat);
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"alwayscheckupright",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) UserCheckUpright = (ddat!=0);
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"showjoints",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) ShowJoints = (ddat!=0);
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"showangles",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) ShowAngles = (ddat!=0);
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"showinvisibles",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) ShowInvisibles = (ddat!=0);
//
size=sizeof(dat); *dat=0; res=RegQueryValueEx(key,"exportfn",NULL,&type,(LPBYTE)&dat,&size); if (res==ERROR_SUCCESS) exportfn=string(dat);
size=sizeof(ddat); ddat=0; res=RegQueryValueEx(key,"exportproc",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exportproc = (ddat!=0);
size=sizeof(dat); *dat=0; res=RegQueryValueEx(key,"exportfigs",NULL,&type,(LPBYTE)&dat,&size); if (res==ERROR_SUCCESS) exportfigs=string(dat);
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"exporttune",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exporttune = ddat;
size=sizeof(dat); *dat=0; res=RegQueryValueEx(key,"exportwav",NULL,&type,(LPBYTE)&dat,&size); if (res==ERROR_SUCCESS) exportwav=string(dat);
size=sizeof(ddat); ddat=128; res=RegQueryValueEx(key,"exportw",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exportw = ddat;
size=sizeof(ddat); ddat=128; res=RegQueryValueEx(key,"exporth",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exporth = ddat;
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"exporttimefixed",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exporttimefixed = (ddat!=0);
size=sizeof(ddat); ddat=10000; res=RegQueryValueEx(key,"exporttime",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exporttime = ddat;
size=sizeof(ddat); ddat=4000; res=RegQueryValueEx(key,"exportproctime",NULL,&type,(LPBYTE)&ddat,&size);if (res==ERROR_SUCCESS) exportproctime = ddat;
size=sizeof(ddat); ddat=20; res=RegQueryValueEx(key,"exportfps",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exportfps=ddat;
size=sizeof(ddat); ddat=1; res=RegQueryValueEx(key,"exportcompress",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exportcompress = (ddat!=0);
size=sizeof(dat); ddat=0; res=RegQueryValueEx(key,"exportopt",NULL,&type,(LPBYTE)&ddat,&size); if (res==ERROR_SUCCESS) exportopt=ddat;
//
RegCloseKey(key);
}
else
{ TUserColour uc;
uc.name="Cyan"; uc.c.r=15; uc.c.g=220; uc.c.b=255; usercols.push_back(uc);
uc.name="Fuchsia"; uc.c.r=255; uc.c.g=10; uc.c.b=180; usercols.push_back(uc);
uc.name="Silver"; uc.c.r=160; uc.c.g=160; uc.c.b=190; usercols.push_back(uc);
}
}
void RegSaveUser()
{ HKEY key; DWORD disp; char buf[10000]; DWORD ddat;
LONG res=RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Lu\\Sticky",0,NULL,0,KEY_WRITE,NULL,&key,&disp);
if (res==ERROR_SUCCESS)
{ WriteUserBacks(buf,10000); RegSetValueEx(key,"userbacks",0,REG_SZ,(CONST BYTE*)&buf,strlen(buf)+1);
WriteUserCols(buf,10000); RegSetValueEx(key,"usercols", 0,REG_SZ,(CONST BYTE*)&buf,strlen(buf)+1);
WriteUserCums(buf,10000); RegSetValueEx(key,"usercums", 0,REG_SZ,(CONST BYTE*)&buf,strlen(buf)+1);
WriteUserThicks(buf,10000);RegSetValueEx(key,"userthick",0,REG_SZ,(CONST BYTE*)&buf,strlen(buf)+1);
ddat=UserSnap?1:0; RegSetValueEx(key,"usersnap",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=UserGrid?1:0; RegSetValueEx(key,"usergrid",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=WhitePrint?1:0; RegSetValueEx(key,"uservert",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=GetRValue(UserBmpBackground); RegSetValueEx(key,"previewbmpbackground",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=UserCheckUpright?1:0; RegSetValueEx(key,"alwayscheckupright",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=ShowJoints?1:0; RegSetValueEx(key,"showjoints",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=ShowAngles?1:0; RegSetValueEx(key,"showangles",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=ShowInvisibles?1:0; RegSetValueEx(key,"showinvisibles",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
//
RegSetValueEx(key,"exportfn",0,REG_SZ,(CONST BYTE*)exportfn.c_str(),exportfn.length()+1);
ddat=exportproc?1:0;RegSetValueEx(key,"exportproc",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
RegSetValueEx(key,"exportfigs",0,REG_SZ,(CONST BYTE*)exportfigs.c_str(),exportfigs.length()+1);
ddat=exporttune; RegSetValueEx(key,"exporttune",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
RegSetValueEx(key,"exportwav",0,REG_SZ,(CONST BYTE*)exportwav.c_str(),exportwav.length()+1);
ddat=exportw; RegSetValueEx(key,"exportw",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=exporth; RegSetValueEx(key,"exporth",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=exporttimefixed?1:0;RegSetValueEx(key,"exporttimefixed",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=exporttime; RegSetValueEx(key,"exporttime",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=exportproctime;RegSetValueEx(key,"exportproctime",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=exportfps; RegSetValueEx(key,"exportfps",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=exportcompress?1:0;RegSetValueEx(key,"exportcompress",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
ddat=exportopt; RegSetValueEx(key,"exportopt",0,REG_DWORD,(CONST BYTE*)&ddat,sizeof(ddat));
//
RegCloseKey(key);
}
}
unsigned int WriteUserCols(char *buf,unsigned int buflen)
{ unsigned int len=0; if (buf!=0 && buflen>0) *buf=0;
for (list<TUserColour>::const_iterator i=usercols.begin(); i!=usercols.end(); i++)
{ char c[1000]; wsprintf(c,"%s=RGB(%i,%i,%i)\r\n",i->name.c_str(),i->c.r,i->c.g,i->c.b);
int cl=strlen(c); if (len+cl<buflen) strcpy(buf+len,c); len+=cl;
}
return len;
}
unsigned int WriteUserCums(char *buf,unsigned int buflen)
{ unsigned int len=0; if (buf!=0 && buflen>0) *buf=0;
if (usercums.size() <= 2) return len;
list<TUserCum>::const_iterator i=usercums.begin(); i++; i++; // get it past the first two fixed ones
for (; i!=usercums.end(); i++)
{ char c[100];
int mul=1;
const char *rate="rate"; if (i->r<0) {rate="fixedrate"; mul=-1;}
const char *reflect=""; if (i->reflect) reflect="reflect_";
sprintf(c,"%s=%s%s(%lg)\r\n",i->name.c_str(),reflect,rate,mul*i->r);
int cl=strlen(c); if (len+cl<buflen) strcpy(buf+len,c); len+=cl;
}
return len;
}
unsigned int WriteUserThicks(char *buf,unsigned int buflen)
{ unsigned int len=0; if (buf!=0 && buflen>0) *buf=0;
for (list<double>::const_iterator i=userthick.begin(); i!=userthick.end(); i++)
{ char c[100]; sprintf(c,"%lg\r\n",*i);
int cl=strlen(c); if (len+cl<buflen) strcpy(buf+len,c); len+=cl;
}
return len;
}
unsigned int WriteUserBacks(char *buf,unsigned int buflen)
{ unsigned int len=0; if (buf!=0 && buflen>0) *buf=0;
for (list<TUserBack>::const_iterator i=UserBacks.begin(); i!=UserBacks.end(); i++)
{ char c[MAX_PATH*3]; wsprintf(c,"%s\r\n%s\r\n",i->fn.c_str(),i->back.c_str());
int cl=strlen(c); if (len+cl<buflen) strcpy(buf+len,c); len+=cl;
}
return len;
}
int ParseUserBacks(const char *dat)
{ UserBacks.clear();
const char *c=dat;
while (*c!=0)
{ const char *start=c; while (*c!='\r' && *c!='\n' && *c!=0) c++;
string fn(start,c-start); fn=StringTrim(fn);
while (*c=='\r' || *c=='\n') c++;
start=c; while (*c!='\r' && *c!='\n' && *c!=0) c++;
string back(start,c-start); back=StringTrim(back);
if (fn!="" && back!="") {TUserBack ub; ub.fn=fn; ub.back=back; UserBacks.push_back(ub);}
while (*c=='\r' || *c=='\n') c++;
}
return -1;
}
int ParseUserCols(const char *dat)
{ const char *c=dat;
list<TUserColour> newcols; int errpos=-1;
while (*c!=0)
{ while (*c==' ') c++;
const char *lstart=c;
while (*c!='=' && *c!='\r' && *c!='\n' && *c!=0) c++;
const char *leq=c; if (*c!='=') leq=0;
while (*c!='\r' && *c!='\n' && *c!=0) c++;
const char *lend=c;
while (*c=='\r' || *c=='\n') c++;
errpos=lstart-dat;
if (lstart!=0 && leq!=0 && lend!=0)
{ TUserColour uc; const char *nstart=lstart, *nend=leq;
while (*nstart==' ') nstart++; while (nend[-1]==' ') nend--;
uc.name=string(nstart,nend);
const char *rgbstart=leq+1; while (*rgbstart==' ') rgbstart++;
int r,g,b; int res=sscanf(rgbstart,"RGB(%i,%i,%i)",&r,&g,&b);
if (res==3)
{ uc.c.r=r; uc.c.g=g; uc.c.b=b; newcols.push_back(uc);
errpos=-1;
}
}
if (errpos!=-1) return errpos;
}
usercols = newcols;
return -1;
}
int ParseUserCums(const char *dat)
{ const char *c=dat;
list<TUserCum> newcums; int errpos=-1;
TUserCum uc; uc.name="Noncumulative"; uc.r=0; uc.reflect=0; newcums.push_back(uc);
uc.name="Cumulative"; uc.r=1; newcums.push_back(uc);
//
while (*c!=0)
{ while (*c==' ') c++; const char *lstart=c;
while (*c!='=' && *c!='\r' && *c!='\n' && *c!=0) c++; const char *leq=c; if (*c!='=') leq=0;
while (*c!='\r' && *c!='\n' && *c!=0) c++; const char *lend=c;
while (*c=='\r' || *c=='\n') c++;
errpos=lstart-dat;
if (lstart!=0 && leq!=0 && lend!=0)
{ TUserCum uc; const char *nstart=lstart, *nend=leq;
while (nend[-1]==' ') nend--; uc.name=string(nstart,nend);
const char *rstart=leq+1; while (*rstart==' ') rstart++;
double r=1; bool reflect=false; int res=0;
if (strncmp(rstart,"rate",4)==0) {res=sscanf(rstart,"rate(%lg)",&r); reflect=false;}
else if (strncmp(rstart,"fixedrate",9)==0) {res=sscanf(rstart,"fixedrate(%lg)",&r); r=-r; reflect=false;}
else if (strncmp(rstart,"reflect_rate",12)==0) {res=sscanf(rstart,"reflect_rate(%lg)",&r); reflect=true;}
else if (strncmp(rstart,"reflect_fixedrate",17)==0) {res=sscanf(rstart,"reflect_fixedrate(%lg)",&r); r=-r; reflect=true;}
if (res==1) {uc.r=r; uc.reflect=reflect; newcums.push_back(uc); errpos=-1;}
}
if (errpos!=-1) return errpos;
}
usercums = newcums;
return -1;
}
int ParseUserThicks(const char *dat)
{ const char *c=dat; list<double> newthick; int errpos=-1;
while (*c!=0)
{ while (*c==' ') c++;
const char *lstart=c;
while (*c!='\r' && *c!='\n' && *c!=0) c++;
const char *lend=c;
while (*c=='\r' || *c=='\n') c++;
errpos = lstart-dat;
if (lstart!=0 && lend!=0)
{ double d; int res=sscanf(lstart,"%lg",&d);
if (res==1)
{ userthick.push_back(d); errpos=-1;
}
}
if (errpos!=-1) return errpos;
}
userthick = newthick;
return -1;
}
enum UserDlgMode {userCols, userThicks, userCums} user;
//
int WINAPI UserDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ if (msg==WM_INITDIALOG) {SetWindowLong(hdlg,DWL_USER,lParam); user=(UserDlgMode)lParam;}
else {user=(UserDlgMode)GetWindowLong(hdlg,DWL_USER);}
//
switch (msg)
{ case WM_INITDIALOG:
{ if (user==userCols) SetWindowText(hdlg,"User Colours");
else if (user==userThicks) SetWindowText(hdlg,"User Thicknesses");
else if (user==userCums) SetWindowText(hdlg,"User Cumulatives");
//
if (user==userCols) SetDlgItemText(hdlg,IDC_TITLE,"List one col per line, e.g. blue=RGB(0,100,255) or pink=RGB(255,0,190)");
else if (user==userThicks) SetDlgItemText(hdlg,IDC_TITLE,"List one thickness per line. 0.0 is thin, 1.0 is medium, 2.0 is thick");
else if (user==userCums) SetDlgItemText(hdlg,IDC_TITLE,"List one cumulative per line, e.g. cdoublespeed=rate(2.0) or c_rain=fixedrate(0.7) or cx=reflect_rate(3.0) or cz=reflect_fixedrate(1)");
//
char buf[10000];
if (user==userCols) WriteUserCols(buf,10000);
else if (user==userThicks) WriteUserThicks(buf,10000);
else if (user==userCums) WriteUserCums(buf,10000);
SetDlgItemText(hdlg,IDC_EDIT,buf);
return TRUE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam); //code=HIWORD(wParam)
if (id==IDCANCEL) {EndDialog(hdlg,IDCANCEL); return TRUE;}
if (id==IDOK)
{ char buf[10000]; GetDlgItemText(hdlg,IDC_EDIT,buf,10000);
int err=-1;
if (user==userCols) err=ParseUserCols(buf);
else if (user==userThicks) err=ParseUserThicks(buf);
else if (user==userCums) err=ParseUserCums(buf);
if (err==-1) {RegSaveUser(); EndDialog(hdlg,IDOK); return TRUE;}
//
string msg,title;
if (user==userCols)
{ title="Unable to read user colours";
msg ="There must be one colour listed on each line.\r\nEach colour must have the form\r\n"
" colname=RGB(r,g,b)\r\n"
"where r,g,b are numbers between 0 and 255 inclusive.";
}
else if (user==userThicks)
{ title="Unable to read user thicknesses";
msg = "There must be one user thickness listed on each line.\r\nEach thickness must "
"be a number.\r\n"
" 0.0 = as thin as possible\r\n"
" 1.0 = medium\r\n"
" 2.0 = heavy";
}
else if (user==userCums)
{ title="Unable to read user cumulatives";
msg = "There must be one cumulative listed on each line.\r\nEach cumulative must be in one of four forms:\r\n"
" cname=rate(r)\r\n"
" cname=fixedrate(r)\r\n"
" cname=reflect_rate(r)\r\n"
" cname=reflect_fixedrate(r)\r\n"
"where r is a number, such as 1.0 for standard speed or 2.0 for double.";
}
int errend=err; while (buf[errend]!='\r' && buf[errend]!='\n' && buf[errend]!=0) errend++;
SendDlgItemMessage(hdlg,IDC_EDIT,EM_SETSEL,err,errend);
SetFocus(GetDlgItem(hdlg,IDC_EDIT));
MessageBox(hdlg,msg.c_str(),title.c_str(),MB_OK);
}
return TRUE;
}
}
return FALSE;
}
void TEditor::UserColours(HWND hpar)
{ DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_USER),hpar,UserDlgProc,userCols);
}
void TEditor::UserThicknesses(HWND hpar)
{ DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_USER),hpar,UserDlgProc,userThicks);
}
void TEditor::UserCumulatives(HWND hpar)
{ DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_USER),hpar,UserDlgProc,userCums);
}
int WINAPI RenameDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ char *buf;
#pragma warning( push )
#pragma warning( disable : 4244 4312 )
if (msg==WM_INITDIALOG) {SetWindowLongPtr(hdlg,DWLP_USER,lParam); buf=(char*)lParam;}
else {buf=(char*)GetWindowLongPtr(hdlg,DWLP_USER);}
#pragma warning( pop )
if (buf==0) return FALSE;
//
switch (msg)
{ case WM_INITDIALOG:
{ SetDlgItemText(hdlg,IDC_RENAME,buf);
SetFocus(GetDlgItem(hdlg,IDC_RENAME));
SendDlgItemMessage(hdlg,IDC_RENAME,EM_SETSEL,0,-1);
return FALSE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam);
if (id==IDOK) GetDlgItemText(hdlg,IDC_RENAME,buf,MAX_PATH);
if (id==IDOK || id==IDCANCEL) EndDialog(hdlg,id);
return TRUE;
}
}
return FALSE;
}
LRESULT CALLBACK ListSubclassProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ HWND hpar = GetParent(hwnd); if (hpar==0) return DefWindowProc(hwnd,msg,wParam,lParam);
LONG_PTR oldproc = GetWindowLongPtr(hpar,GWLP_USERDATA); if (oldproc==0) return DefWindowProc(hwnd,msg,wParam,lParam);
switch (msg)
{ case WM_RBUTTONDOWN:
{ LRESULT sel = SendMessage(hwnd,LB_ITEMFROMPOINT,0,lParam);
BOOL isnothing = HIWORD(sel);
if (isnothing) SendMessage(hwnd,LB_SETCURSEL,(WPARAM)-1,0);
else SendMessage(hwnd,LB_SETCURSEL,sel,0);
int id=GetWindowLongPtr(hwnd,GWLP_ID);
SendMessage(hpar,WM_COMMAND,(WPARAM)(id|(LBN_SELCHANGE<<16)),(LPARAM)hwnd);
SendMessage(hpar,WM_COMMAND,(WPARAM)(id|(BN_CLICKED<<16)),(LPARAM)hwnd);
} break;
}
return CallWindowProc((WNDPROC)oldproc,hwnd,msg,wParam,lParam);
}
int WINAPI BitmapsDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ TEditor *editor;
#pragma warning( push )
#pragma warning( disable : 4244 4312 )
if (msg==WM_INITDIALOG) {SetWindowLongPtr(hdlg,DWLP_USER,lParam); editor=(TEditor*)lParam;}
else {editor=(TEditor*)GetWindowLongPtr(hdlg,DWLP_USER);}
#pragma warning( pop )
if (editor==NULL) return FALSE;
TBody *body = editor->body;
//
switch (msg)
{ case WM_INITDIALOG:
{ // subclass the listbox
HWND hlb = GetDlgItem(hdlg,IDC_LIST);
LONG_PTR oldproc = GetWindowLongPtr(hlb,GWLP_WNDPROC);
SetWindowLongPtr(hdlg,GWLP_USERDATA,oldproc);
SetWindowLongPtr(hlb,GWLP_WNDPROC,(LONG_PTR)ListSubclassProc);
SendMessage(hdlg,WM_APP,TRUE,0);
return TRUE;
}
case WM_APP:
{ if (wParam)
{ // first reset the contents of the list box
const char *sel = (const char*)lParam;
SendDlgItemMessage(hdlg,IDC_LIST,LB_RESETCONTENT,0,0);
for (vector<TBmp>::const_iterator ci=body->bmps.begin(); ci!=body->bmps.end(); ci++)
{ const char *c = ci->name.c_str();
SendDlgItemMessage(hdlg,IDC_LIST,LB_ADDSTRING,0,(LPARAM)c);
}
if (body->bmps.size()>0)
{ int seli=0;
if (sel!=0) seli=SendDlgItemMessage(hdlg,IDC_LIST,LB_FINDSTRINGEXACT,(WPARAM)-1,(LPARAM)sel);
SendDlgItemMessage(hdlg,IDC_LIST,LB_SETCURSEL,seli,0);
}
}
// second ensure that the thing is redrawn
RECT rc; GetWindowRect(GetDlgItem(hdlg,IDC_PICTURE),&rc);
ScreenToClient(hdlg,(POINT*)&rc.left); ScreenToClient(hdlg,(POINT*)&rc.right);
InvalidateRect(hdlg,&rc,FALSE);
return TRUE;
}
case WM_LBUTTONDOWN:
{ POINT pt; pt.x=LOWORD(lParam); pt.y=HIWORD(lParam);
RECT rc; GetWindowRect(GetDlgItem(hdlg,IDC_PICTURE),&rc);
ScreenToClient(hdlg,(POINT*)&rc.left); ScreenToClient(hdlg,(POINT*)&rc.right);
if (PtInRect(&rc,pt))
{ int c=GetRValue(UserBmpBackground);
c+=64; if (c==256) c=255; if (c>256) c=0;
UserBmpBackground=RGB(c,c,c);
SendMessage(hdlg,WM_APP,FALSE,0);
}
return TRUE;
}
case WM_PAINT:
{ PAINTSTRUCT ps; BeginPaint(hdlg,&ps);
RECT rc; GetWindowRect(GetDlgItem(hdlg,IDC_PICTURE),&rc);
ScreenToClient(hdlg,(POINT*)&rc.left); ScreenToClient(hdlg,(POINT*)&rc.right);
HBRUSH hbr = CreateSolidBrush(UserBmpBackground);
FillRect(ps.hdc,&rc,hbr);
DeleteObject(hbr);
int seli = SendDlgItemMessage(hdlg,IDC_LIST,LB_GETCURSEL,0,0);
if (seli!=LB_ERR)
{ char c[MAX_PATH]; SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXT,seli,(LPARAM)c);
for (vector<TBmp>::const_iterator ci=body->bmps.begin(); ci!=body->bmps.end(); ci++)
{ if (_stricmp(ci->name.c_str(),c)==0)
{ HDC tdc = CreateCompatibleDC(ps.hdc);
BITMAP bmp; GetObject(ci->hbm,sizeof(bmp),&bmp); int bwidth=bmp.bmWidth, bheight=bmp.bmHeight;
SetStretchBltMode(ps.hdc,COLORONCOLOR);
int x,y,w,h;
double fb=((double)bwidth)/((double)bheight), fr=((double)(rc.right-rc.left))/((double)(rc.bottom-rc.top));
if (fb>fr)
{ x=rc.left; w=rc.right-rc.left;
double f = ((double)w)/((double)bwidth);
h=(int)(bheight*f);
y=rc.top + (rc.bottom-rc.top-h)/2;
}
else
{ y=rc.top; h=rc.bottom-rc.top;
double f = ((double)h)/((double)bheight);
w=(int)(bwidth*f);
x=rc.left + (rc.right-rc.left-w)/2;
}
// do it with the mask
HGDIOBJ hold;
if (ci->hbmask!=0)
{ hold = SelectObject(tdc,ci->hbmask);
StretchBlt(ps.hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCAND);
SelectObject(tdc,ci->hbm);
StretchBlt(ps.hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCPAINT);
}
else
{ hold = SelectObject(tdc,ci->hbm);
StretchBlt(ps.hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCCOPY);
}
SelectObject(tdc,hold);
DeleteDC(tdc);
}
}
}
EndPaint(hdlg,&ps);
return TRUE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (id==IDOK || id==IDCANCEL) EndDialog(hdlg,id);
else if (id==IDC_LIST && code==LBN_SELCHANGE)
{ SendMessage(hdlg,WM_APP,FALSE,0);
}
else if (id==IDC_LIST && code==BN_CLICKED)
{ int seli = SendDlgItemMessage(hdlg,IDC_LIST,LB_GETCURSEL,0,0);
char c[MAX_PATH];
if (seli==LB_ERR) *c=0; else SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXT,seli,(LPARAM)c);
string oldname(c);
//
enum {rmAdd=101, rmDelete=102, rmRename=13};
HMENU hrightmenu = CreatePopupMenu();
if (seli!=LB_ERR)
{ im(hrightmenu,"Rename",rmRename);
im(hrightmenu,"Delete",rmDelete);
}
im(hrightmenu,"Add",rmAdd);
//
POINT pt; GetCursorPos(&pt);
int cmd=TrackPopupMenu(hrightmenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,hdlg,NULL);
DestroyMenu(hrightmenu);
if (cmd==rmDelete)
{ editor->DeleteBitmap(oldname);
SendMessage(hdlg,WM_APP,TRUE,0);
}
else if (cmd==rmRename)
{ int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_RENAME),hdlg,RenameDlgProc,(LPARAM)c);
if (res==IDOK)
{ string newname(c);
string zn = editor->RenameBitmap(oldname,newname);
SendMessage(hdlg,WM_APP,TRUE,(LPARAM)zn.c_str());
}
}
else if (cmd==rmAdd) SendMessage(hdlg,WM_COMMAND,(WPARAM)(IDC_ADD|(BN_CLICKED<<16)),0);
}
else if (id==IDC_ADD && code==BN_CLICKED)
{ char tfn[MAX_PATH*20]; *tfn=0;
OPENFILENAME ofn; ZeroMemory(&ofn,sizeof(ofn));
ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=hdlg;
ofn.lpstrFilter= "Bitmaps and Jpegs\0*.bmp;*.jpg;*.jpeg\0";
ofn.lpstrFile=tfn;
ofn.nMaxFile=MAX_PATH*20;
ofn.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY|OFN_ALLOWMULTISELECT|OFN_EXPLORER;
ofn.lpstrDefExt = "bmp";
BOOL res = GetOpenFileName(&ofn);
if (!res) return FALSE;
string zn="";
string dir=tfn; const char *fn=tfn+dir.length()+1;
// either there was just a single filepath, or a dir followed by a list of filenames
//
editor->MarkUndo(true);
if (*fn==0) zn = editor->AddBitmap(dir.c_str());
else while (*fn!=0)
{ string s = dir+"\\"+fn;
zn = editor->AddBitmap(s.c_str());
fn=fn+strlen(fn)+1;
}
MakeBindexes(body);
editor->ismodified=true;
editor->Redraw();
SendMessage(hdlg,WM_APP,TRUE,(LPARAM)zn.c_str());
}
return TRUE;
}
}
return FALSE;
}
void TEditor::Bitmaps(HWND hpar)
{ DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_BITMAPS),hpar,BitmapsDlgProc,(LPARAM)this);
}
string TEditor::StyleClick(HWND hpar,const string s)
{ TStyle *style=0; list<TStyle>::iterator styleiterator=body->styles.begin();
if (s!="")
{ while (styleiterator!=body->styles.end() && StringLower(styleiterator->name)!=StringLower(s)) styleiterator++;
if (styleiterator!=body->styles.end()) style=&(*styleiterator);
}
//
enum {smDelete=1, smRename=2, smAdd=3,
smFillVisible=12, smFillInvisible=13, smFillAlternate=14, smFillWinding=15, smFillMore=16, smFill=17, smFillLast=49,
smLineVisible=50, smLineInvisible=51, smLineMore=52, smLineExtra2=53, smLineExtra1=54, smLineThick=55, smLineMedium=56, smLineThin=57, smLine=58, smLineLast=99,
smFreqFixed=111, smFreqNegative=113, smFreqLeft=114, smFreqRight=125, smFreqDifference=135, smFreqKaraoke=145,
smMoreBitmaps=180, smBitmaps=181, smBitmapsLast=250,
smShortNone=251,smShortFirst=252,smShortLast=299,
smMoreEffects=300, smLineEffectsFirst=301, smLineEffectsLast=399,
smFillEffectsFirst=400, smFillEffectsLast=499,
smMoreCums=500,smCumsFirst=501,smCumsLast=599};
HMENU hstylemenu=CreatePopupMenu();
HMENU hlinemenu=CreatePopupMenu(), hfillmenu=CreatePopupMenu(), hfreqmenu=CreatePopupMenu();
HMENU hshortmenu=CreatePopupMenu();
vector<COLORREF> extracols;
MENUITEMINFO mi; ZeroMemory(&mi,sizeof(mi)); mi.cbSize=sizeof(mi);
//
// styles
im(hstylemenu,"Add",smAdd);
if (style!=0)
{ im(hstylemenu,"Delete",smDelete);
im(hstylemenu,"Rename",smRename);
}
//
// shortcut
if (style!=0)
{ vector<bool> available; available.resize(20,true);
for (list<TStyle>::const_iterator i=body->styles.begin(); i!=body->styles.end(); i++)
{ if (i->shortcut!=0) available[i->shortcut-'A']=false;
}
int shortcut=-1;
if (style->shortcut!=0) {shortcut=style->shortcut-'A'; available[shortcut]=true;}
im(hshortmenu,"None",smShortNone,shortcut==-1,true,true);
for (int i=19; i>=0; i--)
{ char c = (char)('A'+i);
string s = "Ctrl+"+string(&c,1);
if (c!='C') im(hshortmenu,s,smShortFirst+i,shortcut==i,available[i],true);
}
im(hstylemenu,"Shortcut",hshortmenu);
im(hstylemenu,"--");
}
//
// Fill
if (style!=0)
{ bool isvisible = (style->shape.brush.type!=ctNone);
list<COLORREF> cols; if (style->shape.brush.type==ctRGB) cols.push_back(CREF(style->shape.brush.rgb));
list<string> effects; if (style->limb.color.type==ctEffect) effects.push_back(style->limb.color.effect);
//
im(hfillmenu,"Effects...",smMoreEffects);
im(hfillmenu,body->effects,effects,style->shape.brush.type!=ctEffect,smFillEffectsFirst);
im(hfillmenu,"--");
im(hfillmenu,"Bitmaps...",smMoreBitmaps);
for (int bic=0; bic<(int)body->bmps.size(); bic++)
{ string bname = body->bmps[bic].name;
bool checked = (StringLower(bname)==StringLower(style->shape.brush.bitmap));
checked &= (style->shape.brush.type==ctBitmap);
im(hfillmenu,bname,smBitmaps+bic,checked,true,true);
}
im(hfillmenu,"--");
im(hfillmenu,"Colours...",smFillMore);
im(hfillmenu,cols,style->shape.brush.type!=ctRGB,smFill,false,&extracols);
im(hfillmenu,"--");
im(hfillmenu,"Invisible",isvisible?smFillInvisible:smFillVisible,!isvisible,true,false);
im(hstylemenu,"Fill",hfillmenu);
}
//
// Line
if (style!=0)
{ list<COLORREF> cols; if (style->limb.color.type==ctRGB) cols.push_back(CREF(style->limb.color.rgb));
list<string> effects; if (style->limb.color.type==ctEffect) effects.push_back(style->limb.color.effect);
int thick; if (style->limb.thickness<0.5) thick=0; else if (style->limb.thickness<1.5) thick=1;
else if (style->limb.thickness<3) thick=2; else if (style->limb.thickness<6) thick=3; else thick=4;
if (style->limb.color.type==ctNone) thick=-1;
//
im(hlinemenu,"Effects...",smMoreEffects);
im(hlinemenu,body->effects,effects,style->limb.color.type!=ctEffect,smLineEffectsFirst,imDisallowBitmaps);
im(hlinemenu,"--");
im(hlinemenu,"Colours...",smLineMore);
im(hlinemenu,cols,style->limb.color.type!=ctRGB,smLine,false,&extracols);
im(hlinemenu,"--");
im(hlinemenu,"Extra2",smLineExtra2,thick==4);
im(hlinemenu,"Extra",smLineExtra1,thick==3);
im(hlinemenu,"Heavy",smLineThick,thick==2);
im(hlinemenu,"Medium",smLineMedium,thick==1);
im(hlinemenu,"Thin",smLineThin,thick==0);
im(hlinemenu,"--");
im(hlinemenu,"Invisible",style->limb.color.type==ctNone?smLineVisible:smLineInvisible,style->limb.color.type==ctNone,true,false);
im(hstylemenu,"Line",hlinemenu);
}
//
// Frequency
vector<CumInfo> retcums;
if (style!=0)
{ int chan=style->limb.chan, band=style->limb.band;
list<CumInfo> cums; if (style->limb.cum) cums.push_back(CumInfo(style->limb.crate,style->limb.creflect)); else cums.push_back(CumInfo(0,0));
//
im(hfreqmenu,"Cumulatives...",smMoreCums);
im(hfreqmenu,cums,smCumsFirst,retcums);
im(hfreqmenu,"Negative",smFreqNegative,style->limb.negative,true,false);
im(hfreqmenu,"--");
im(hfreqmenu,"Music", smFreqKaraoke+1, chan==3&&band==1);
im(hfreqmenu,"Vocals",smFreqKaraoke+0, chan==3&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Difference: 6",smFreqDifference+5, chan==2&&band==5);
im(hfreqmenu,"Difference: 5",smFreqDifference+4, chan==2&&band==4);
im(hfreqmenu,"Difference: 4",smFreqDifference+3, chan==2&&band==3);
im(hfreqmenu,"Difference: 3",smFreqDifference+2, chan==2&&band==2);
im(hfreqmenu,"Difference: 2",smFreqDifference+1, chan==2&&band==1);
im(hfreqmenu,"Difference: 1",smFreqDifference+0, chan==2&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Right: 6 treble",smFreqRight+5, chan==1&&band==5);
im(hfreqmenu,"Right: 5",smFreqRight+4, chan==1&&band==4);
im(hfreqmenu,"Right: 4",smFreqRight+3, chan==1&&band==3);
im(hfreqmenu,"Right: 3",smFreqRight+2, chan==1&&band==2);
im(hfreqmenu,"Right: 2",smFreqRight+1, chan==1&&band==1);
im(hfreqmenu,"Right: 1 bass",smFreqRight+0, chan==1&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Left: 6 treble",smFreqLeft+5, chan==0&&band==5);
im(hfreqmenu,"Left: 5",smFreqLeft+4, chan==0&&band==4);
im(hfreqmenu,"Left: 4",smFreqLeft+3, chan==0&&band==3);
im(hfreqmenu,"Left: 3",smFreqLeft+2, chan==0&&band==2);
im(hfreqmenu,"Left: 2",smFreqLeft+1, chan==0&&band==1);
im(hfreqmenu,"Left: 1 bass",smFreqLeft+0, chan==0&&band==0);
im(hfreqmenu,"--");
im(hfreqmenu,"Fixed",smFreqFixed, chan==4&&band==0);
im(hstylemenu,"Frequency",hfreqmenu);
}
//
POINT pt; GetCursorPos(&pt);
BalanceMenu(hstylemenu); BalanceMenu(hfreqmenu);
BalanceMenu(hlinemenu); BalanceMenu(hfillmenu);
int cmd=TrackPopupMenu(hstylemenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,hpar,NULL);
DestroyMenu(hstylemenu);
DestroyMenu(hfreqmenu);
DestroyMenu(hlinemenu);
DestroyMenu(hfillmenu);
DestroyMenu(hshortmenu);
if (cmd==0) return s;
//
MarkUndo();
ismodified=true;
if (cmd==smLineVisible && style->limb.color.type==ctNone) style->limb.color.type=style->limb.color.otype;
else if (cmd==smShortNone) {style->shortcut=0; return style->name;}
else if (cmd>=smShortFirst && cmd<=smShortLast) {style->shortcut=(char)(cmd-smShortFirst+'A'); return style->name;}
else if (cmd==smAdd)
{ string name=CleanStyleName("NewStyle");
TStyle s; s.name=name; body->styles.push_back(s);
return name;
}
else if (cmd==smRename || cmd==smDelete)
{ string lcoldname=StringLower(style->name),newname("");
if (cmd==smRename)
{ char c[100]; strcpy(c,style->name.c_str());
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_RENAME),hpar,RenameDlgProc,(LPARAM)c);
if (res!=IDOK) return style->name;
newname=CleanStyleName(c);
}
for (int i=0; i<body->nlimbs; i++)
{ if (StringLower(body->limbs[i].linestyle)==lcoldname) body->limbs[i].linestyle=newname;
if (StringLower(body->limbs[i].freqstyle)==lcoldname) body->limbs[i].freqstyle=newname;
}
for (vector<stk::TShape>::iterator si=body->shapes.begin(); si!=body->shapes.end(); si++)
{ if (StringLower(si->fillstyle)==lcoldname) si->fillstyle=newname;
if (StringLower(si->linestyle)==lcoldname) si->linestyle=newname;
}
style->name=newname;
if (cmd==smDelete)
{ body->styles.erase(styleiterator);
}
return newname;
}
else if (cmd==smLineInvisible) {if (style->limb.color.type!=ctNone) style->limb.color.otype=style->limb.color.type; style->limb.color.type=ctNone;}
else if (cmd==smFillVisible && style->shape.brush.type==ctNone) style->shape.brush.type=style->shape.brush.otype;
else if (cmd==smFillInvisible) {if (style->shape.brush.type!=ctNone) style->shape.brush.otype=style->shape.brush.type; style->shape.brush.type=ctNone;}
else if (cmd==smFillMore||cmd==smLineMore) {UserColours(hpar); return style->name;}
else if (cmd==smMoreBitmaps) {Bitmaps(hpar); return style->name;}
else if (cmd>=smBitmaps && cmd<=smBitmapsLast) {style->shape.brush.type=ctBitmap; style->shape.brush.bitmap=body->bmps[cmd-smBitmaps].name;}
else if (cmd==smFreqNegative) style->limb.negative = !style->limb.negative;
else if (cmd>=smFreqDifference && cmd<=smFreqDifference+5) {style->limb.chan=2; style->limb.band=cmd-smFreqDifference;}
else if (cmd>=smFreqLeft && cmd<=smFreqLeft+5) {style->limb.chan=0; style->limb.band=cmd-smFreqLeft;}
else if (cmd>=smFreqRight && cmd<=smFreqRight+5) {style->limb.chan=1; style->limb.band=cmd-smFreqRight;}
else if (cmd>=smFreqKaraoke && cmd<=smFreqKaraoke+5) {style->limb.chan=3; style->limb.band=cmd-smFreqKaraoke;}
else if (cmd==smFreqFixed) {style->limb.chan=4; style->limb.band=0;}
else if (cmd==smLineExtra2) {style->limb.thickness=8.0; if (style->limb.color.type==ctNone) style->limb.color.type=style->limb.color.otype;}
else if (cmd==smLineExtra1) {style->limb.thickness=4.0; if (style->limb.color.type==ctNone) style->limb.color.type=style->limb.color.otype;}
else if (cmd==smLineThick) {style->limb.thickness=2.0; if (style->limb.color.type==ctNone) style->limb.color.type=style->limb.color.otype;}
else if (cmd==smLineMedium) {style->limb.thickness=1.0; if (style->limb.color.type==ctNone) style->limb.color.type=style->limb.color.otype;}
else if (cmd==smLineThin) {style->limb.thickness=0.0; if (style->limb.color.type==ctNone) style->limb.color.type=style->limb.color.otype;}
else if (cmd==smMoreEffects) Effects(hpar);
else if (cmd>=smLineEffectsFirst && cmd<=smLineEffectsLast) {style->limb.color.type=ctEffect; style->limb.color.effect=body->effects[cmd-smLineEffectsFirst].name;}
else if (cmd>=smFillEffectsFirst && cmd<=smFillEffectsLast) {style->shape.brush.type=ctEffect; style->shape.brush.effect=body->effects[cmd-smFillEffectsFirst].name;}
else if (cmd==smMoreCums) UserCumulatives(hpar);
else if (cmd>=smCumsFirst && cmd<=smCumsLast)
{ double d = retcums[cmd-smCumsFirst].d;
int r = retcums[cmd-smCumsFirst].r;
if (d==0) {style->limb.cum=false;}
else {style->limb.cum=true; style->limb.crate=d; style->limb.creflect=r;}
}
else if ((cmd>=smLine && cmd<=smLineLast) || (cmd>=smFill && cmd<=smFillLast))
{ TSetSubject subj=tsLine; int c=cmd-smLine;
if (cmd>=smFill && cmd<=smFillLast) {subj=tsFill; c=cmd-smFill;}
int r,g,b;
if (c<ncols)
{ r=defcols[c].r; g=defcols[c].g; b=defcols[c].b;
}
else if (c<ncols+(int)usercols.size())
{ int ci=ncols; list<TUserColour>::const_iterator ui=usercols.begin();
while (ci<c) {ci++; ui++;}
r=ui->c.r; g=ui->c.g; b=ui->c.b;
}
else
{ int e=c-ncols-(int)usercols.size(); COLORREF cl=extracols[e];
r=GetRValue(cl); g=GetGValue(cl); b=GetBValue(cl);
}
if (subj==tsLine) {style->limb.color.type=ctRGB; style->limb.color.rgb=RGBCOLOR(r,g,b);}
else {style->shape.brush.type=ctRGB; style->shape.brush.rgb=RGBCOLOR(r,g,b);}
}
//
// And now propogate the changes through the document
ApplyStyle(style->name);
Redraw(); SetCursor();
//
return style->name;
}
TStyle TEditor::StyleFromName(const string name)
{ if (name=="") {TStyle s; s.name=""; return s;}
string lcname=StringLower(name);
list<TStyle>::const_iterator si=body->styles.begin();
while (si!=body->styles.end() && StringLower(si->name)!=lcname) si++;
if (si==body->styles.end()) {TStyle s; s.name=""; return s;}
else return *si;
}
void TEditor::ApplyStyle(const string name,bool suppressredraw)
{ bool anybmp=false;
string lcname = StringLower(name);
list<TStyle>::const_iterator si=body->styles.begin();
while (si!=body->styles.end() && StringLower(si->name)!=lcname) si++;
if (si==body->styles.end()) return;
const TStyle &style = *si;
//
for (int i=0; i<body->nlimbs; i++)
{ TLimb &limb = body->limbs[i];
if (StringLower(limb.linestyle)==lcname)
{ limb.color=style.limb.color;
limb.thickness=style.limb.thickness;
}
if (StringLower(limb.freqstyle)==lcname)
{ limb.chan=style.limb.chan; limb.band=style.limb.band; limb.negative=style.limb.negative;
limb.cum=style.limb.cum; limb.crate=style.limb.crate; limb.creflect=style.limb.creflect;
RepositioningMove(i,b2x(limb.x),b2y(limb.y),true);
}
}
for (int si=0; si<(int)body->shapes.size(); si++)
{ stk::TShape &shape = body->shapes[si];
if (StringLower(shape.linestyle)==lcname)
{ shape.line=style.limb.color;
shape.thickness=style.limb.thickness;
}
if (StringLower(shape.fillstyle)==lcname)
{ if (style.shape.brush.type!=ctBitmap) {shape.brush=style.shape.brush;}
else
{ // we can't assign a bitmap to anything other than a circle
int li = circlelimb_from_shape(si);
if (li!=-1) {shape.brush=style.shape.brush; anybmp=true;}
}
}
}
if (!suppressredraw)
{ if (anybmp) MakeBindexes(body);
MakeEindexes(body);
Recalc(0);
}
}
string TEditor::CleanStyleName(const string s)
{ string broot=s;
for (int i=0; i<(int)broot.size(); i++)
{ if (broot[i]==')') broot[i]=']';
if (broot[i]=='(') broot[i]='[';
if (broot[i]=='=') broot[i]='-';
}
for (int i=1; ; i++)
{ string bname;
if (i==1) bname=broot; else bname=broot+StringInt(i);
bool okay=true;
for (list<TStyle>::const_iterator si=body->styles.begin(); si!=body->styles.end() && okay; si++)
{ if (StringLower(si->name)==StringLower(bname)) okay=false;
}
if (okay) return bname;
}
}
int WINAPI StylesDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ TEditor *editor;
#pragma warning( push )
#pragma warning( disable : 4244 4312 )
if (msg==WM_INITDIALOG) {SetWindowLongPtr(hdlg,DWLP_USER,lParam); editor=(TEditor*)lParam;}
else {editor=(TEditor*)GetWindowLongPtr(hdlg,DWLP_USER);}
#pragma warning( pop )
if (editor==NULL) return FALSE;
TBody *body = editor->body;
//
switch (msg)
{ case WM_INITDIALOG:
{ // subclass the listbox
HWND hlb = GetDlgItem(hdlg,IDC_LIST);
LONG_PTR oldproc = GetWindowLongPtr(hlb,GWLP_WNDPROC);
SetWindowLongPtr(hdlg,GWLP_USERDATA,oldproc);
SetWindowLongPtr(hlb,GWLP_WNDPROC,(LONG_PTR)ListSubclassProc);
SendMessage(hdlg,WM_APP,0,0);
return TRUE;
}
case WM_APP:
{ // reset the contents of the list box
const char *csel = (const char*)lParam;
SendDlgItemMessage(hdlg,IDC_LIST,LB_RESETCONTENT,0,0);
for (list<TStyle>::const_iterator si=body->styles.begin(); si!=body->styles.end(); si++)
{ string s = si->tostring();
SendDlgItemMessage(hdlg,IDC_LIST,LB_ADDSTRING,0,(LPARAM)s.c_str());
}
if (body->styles.size()>0)
{ int seli=0;
if (csel!=0) seli=SendDlgItemMessage(hdlg,IDC_LIST,LB_FINDSTRING,(WPARAM)-1,(LPARAM)(string(csel)+"=").c_str());
SendDlgItemMessage(hdlg,IDC_LIST,LB_SETCURSEL,seli,0);
}
return TRUE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (id==IDOK || id==IDCANCEL) EndDialog(hdlg,id);
else if (id==IDC_LIST && code==BN_CLICKED)
{ int seli = SendDlgItemMessage(hdlg,IDC_LIST,LB_GETCURSEL,0,0);
string oldname="";
if (seli!=LB_ERR)
{ int len = SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXTLEN,seli,0);
char *c=new char[len+1]; SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXT,seli,(LPARAM)c);
char *eq=strchr(c,'='); if (eq!=0) *eq=0;
oldname=c; delete[] c;
}
const string newname = editor->StyleClick(hdlg,oldname);
SendMessage(hdlg,WM_APP,0,(LPARAM)newname.c_str());
}
return TRUE;
}
}
return FALSE;
}
void TEditor::Styles(HWND hpar)
{ DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_STYLES),hpar,StylesDlgProc,(LPARAM)this);
}
vector<TEffect>::const_iterator get_effect(const vector<TEffect> &effects,const string name)
{ vector<TEffect>::const_iterator ei = effects.begin();
while (ei!=effects.end() && StringLower(ei->name)!=StringLower(name)) ei++;
return ei;
}
vector<TEffect>::iterator get_effect(vector<TEffect> &effects,const string name)
{ vector<TEffect>::iterator ei = effects.begin();
while (ei!=effects.end() && StringLower(ei->name)!=StringLower(name)) ei++;
return ei;
}
struct EffectsDlgData
{ EffectsDlgData() : editor(0), editup(false), dragging(-2) {}
TEditor *editor; bool editup;
unsigned int timeStart,timePrev; int samplei;
// the following is used only internally for EffectWndProc
string seffect; // [in/out]
TEffect effect;
RECT rc; int w,h; // rc is the rect of the segmented bar.
int knobx,knoby;
int dragging; // 0..n-1=line to right of segment. -1=knob. -2=nothing.
};
LRESULT CALLBACK EffectWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ EffectsDlgData *dat;
#pragma warning( push )
#pragma warning( disable : 4244 4312 )
if (msg==WM_CREATE) {CREATESTRUCT *cs=(CREATESTRUCT*)lParam; SetWindowLongPtr(hwnd,GWLP_USERDATA,(LONG_PTR)cs->lpCreateParams); dat=(EffectsDlgData*)cs->lpCreateParams;}
else {dat=(EffectsDlgData*)GetWindowLongPtr(hwnd,GWLP_USERDATA);}
#pragma warning( pop )
if (dat==NULL) return DefWindowProc(hwnd,msg,wParam,lParam);
TEffect &effect = dat->effect;
TEditor *editor = dat->editor;
TBody *body = dat->editor->body;
//
switch (msg)
{ case WM_CREATE:
{ dat->effect.fromstring(dat->seffect);
RECT rc; GetClientRect(hwnd,&rc); dat->w=rc.right; dat->h=rc.bottom;
dat->rc.left=dat->w/6; dat->rc.top=dat->h/6; dat->rc.right=dat->w*5/6; dat->rc.bottom=dat->h*4/6;
dat->knoby=dat->h*5/6;
double dx=effect.f*(double)dat->w;
dat->knobx=dat->rc.left+(int)dx;
} return 0;
case WM_COMMAND:
{ int id=LOWORD(wParam);
if (id==IDOK) {dat->seffect=effect.tostring(); DestroyWindow(hwnd);}
} return 0;
case WM_PAINT:
{ PAINTSTRUCT ps; BeginPaint(hwnd,&ps);
double tot=0; for (unsigned int segment=0; segment<effect.cols.size(); segment++)
{ double nexttot=tot+effect.fracs[segment]; if (segment==effect.cols.size()-1) nexttot=1;
stk::TColor col=effect.cols[segment], nextcol=effect.cols[(segment+1)%effect.cols.size()];
double dw=dat->rc.right-dat->rc.left;
int x0=dat->rc.left+(int)(tot*dw), x1=dat->rc.left+(int)(nexttot*dw);
RECT rc; rc.left=x0; rc.top=dat->rc.top; rc.right=x1; rc.bottom=dat->rc.bottom;
tot=nexttot;
//
if (col.type==ctNone || col.type==ctBitmap) FillRect(ps.hdc,&rc,(HBRUSH)GetStockObject(BLACK_BRUSH));
else if (col.type==ctRGB)
{
LOGBRUSH lbr; lbr.lbStyle = BS_SOLID; lbr.lbColor = RGB(col.rgb.r, col.rgb.g, col.rgb.b);
if (col.fadetonext && nextcol.type==ctRGB)
{ for (int x=x0; x<x1; x+=5)
{ double r1=col.rgb.r, g1=col.rgb.g, b1=col.rgb.b;
double r2=nextcol.rgb.r, g2=nextcol.rgb.g, b2=nextcol.rgb.b;
double f = ((double)(x-x0))/((double)(x1-x0));
double r=r1*(1-f)+r2*f, g=g1*(1-f)+g2*f, b=b1*(1-f)+b2*f;
lbr.lbColor=RGB((int)r,(int)g,(int)b);
HBRUSH hbr=CreateBrushIndirect(&lbr);
RECT src; src.left=x; src.top=rc.top; src.right=x+5; src.bottom=rc.bottom; if (src.right>rc.right) src.right=rc.right;
FillRect(ps.hdc,&src,hbr);
DeleteObject(hbr);
}
}
else
{ lbr.lbColor=RGB(col.rgb.r,col.rgb.g,col.rgb.b);
HBRUSH hbr=CreateBrushIndirect(&lbr);
FillRect(ps.hdc,&rc,hbr);
DeleteObject(hbr);
}
}
else LUASSERTMM("unknown col type");
//
if (col.type==ctNone)
{ SelectObject(ps.hdc,GetStockObject(WHITE_PEN));
MoveToEx(ps.hdc,rc.left,rc.top,0); LineTo(ps.hdc,rc.right,rc.bottom);
MoveToEx(ps.hdc,rc.right,rc.top,0); LineTo(ps.hdc,rc.left,rc.bottom);
}
if (col.type==ctBitmap)
{ HDC tdc = CreateCompatibleDC(ps.hdc);
int bindex=body->bindex(col.bitmap); LUASSERT(bindex!=-1);
const TBmp &bitmap = body->bmps[bindex];
BITMAP bmp; GetObject(bitmap.hbm,sizeof(bmp),&bmp); int bwidth=bmp.bmWidth, bheight=bmp.bmHeight;
SetStretchBltMode(ps.hdc,COLORONCOLOR);
int x,y,w,h;
double fb=((double)bwidth)/((double)bheight), fr=((double)(rc.right-rc.left))/((double)(rc.bottom-rc.top));
if (fb>fr)
{ x=rc.left; w=rc.right-rc.left;
double f = ((double)w)/((double)bwidth);
h=(int)(bheight*f);
y=rc.top + (rc.bottom-rc.top-h)/2;
}
else
{ y=rc.top; h=rc.bottom-rc.top;
double f = ((double)h)/((double)bheight);
w=(int)(bwidth*f);
x=rc.left + (rc.right-rc.left-w)/2;
}
// do it with the mask
HGDIOBJ hold;
if (bitmap.hbmask!=0)
{ hold = SelectObject(tdc,bitmap.hbmask);
StretchBlt(ps.hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCAND);
SelectObject(tdc,bitmap.hbm);
StretchBlt(ps.hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCPAINT);
}
else
{ hold = SelectObject(tdc,bitmap.hbm);
StretchBlt(ps.hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCCOPY);
}
SelectObject(tdc,hold);
DeleteDC(tdc);
}
}
//
tot=0; for (unsigned int segment=0; segment<effect.cols.size()-1; segment++)
{ double dw=dat->rc.right-dat->rc.left;
tot+=effect.fracs[segment]; int x=dat->rc.left+(int)(tot*dw);
RECT rc; rc.left=x-2; rc.right=x+2; rc.top=dat->rc.top; rc.bottom=dat->rc.bottom;
FillRect(ps.hdc,&rc,(HBRUSH)GetStockObject(WHITE_BRUSH));
rc.left++; rc.right--; rc.top++; rc.bottom--;
FillRect(ps.hdc,&rc,(HBRUSH)GetStockObject(BLACK_BRUSH));
}
//
RECT rc;
rc.left=dat->rc.left; rc.top=dat->knoby-1; rc.right=dat->knobx; rc.bottom=dat->knoby+1;
FillRect(ps.hdc,&rc,(HBRUSH)GetStockObject(WHITE_BRUSH));
rc.left=dat->knobx-4; rc.right=rc.left+8; rc.top=dat->knoby-4; rc.bottom=rc.top+8;
FillRect(ps.hdc,&rc,(HBRUSH)GetStockObject(WHITE_BRUSH));
rc.left=dat->knobx-2; rc.right=rc.left+4; rc.top=dat->knoby-2; rc.bottom=rc.top+4;
FillRect(ps.hdc,&rc,(HBRUSH)GetStockObject(BLACK_BRUSH));
//
SelectObject(ps.hdc,GetStockObject(WHITE_PEN));
SelectObject(ps.hdc,GetStockObject(NULL_BRUSH));
Rectangle(ps.hdc,dat->rc.left,dat->rc.top,dat->rc.right,dat->rc.bottom);
//
EndPaint(hwnd,&ps);
} return 0;
case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_SETCURSOR:
{ int x=LOWORD(lParam),y=HIWORD(lParam);
if (msg==WM_SETCURSOR) {POINT pt; GetCursorPos(&pt); ScreenToClient(hwnd,&pt); x=pt.x; y=pt.y;}
int sel=-2; bool online=false;
if (x>=dat->rc.left && x<dat->knobx+4 && y>=dat->knoby-4 && y<dat->knoby+4)
{ sel=-1; online=(x>=dat->knobx-4);
}
else if (x>=dat->rc.left && x<dat->rc.right+4 && y>=dat->rc.top && y<dat->rc.bottom)
{ double tot=0; for (unsigned int segment=0; segment<effect.cols.size(); segment++)
{ double dw=dat->rc.right-dat->rc.left;
tot+=effect.fracs[segment]; if (segment==effect.cols.size()-1) tot=1;
int sx1=dat->rc.left+(int)(tot*dw);
if (x<sx1+4) {sel=(int)segment; online=(x>=sx1-4); break;}
}
}
if (msg==WM_SETCURSOR)
{ if (online) SetCursor(LoadCursor(NULL,IDC_SIZEWE));
else SetCursor(LoadCursor(NULL,IDC_ARROW));
return TRUE;
}
if (sel==-2) return 0;
if (msg==WM_LBUTTONDOWN && sel==(int)effect.cols.size()-1) return 0;
if (msg==WM_LBUTTONDOWN && online) {dat->dragging=sel; return 0;}
if (msg==WM_LBUTTONDOWN && sel==-1) {dat->dragging=sel; return 0;}
if (msg==WM_LBUTTONDOWN) return 0;
//
enum {rmFreqNegative=113, rmFreqLeft=114, rmFreqRight=125, rmFreqDifference=135,
rmFreqCumMore=151,rmFreqCumFirst=152, rmFreqCumLast=200,
rmMoreBitmaps=201, rmBitmaps=202, rmColMore=300, rmColFade=301, rmCol=302,
rmAddAfter=403,rmAddBefore=404,rmDelete=405,
rmFreqKaraoke=406,rmInvisible=420};
vector<COLORREF> extracols;
HMENU hrightmenu=CreatePopupMenu();
vector<CumInfo> retcums;
if (sel==-1)
{ list<CumInfo> cums; if (effect.cumulative) cums.push_back(CumInfo(effect.cumrate,effect.creflect)); else cums.push_back(CumInfo(0,0));
im(hrightmenu,"Cumulatives...",rmFreqCumMore);
im(hrightmenu,cums,rmFreqCumFirst,retcums);
im(hrightmenu,"Negative",rmFreqNegative,effect.negative,true,false);
im(hrightmenu,"--");
im(hrightmenu,"Music", rmFreqKaraoke+1, effect.chan==3&&effect.band==1);
im(hrightmenu,"Vocals",rmFreqKaraoke+0, effect.chan==3&&effect.band==0);
im(hrightmenu,"--");
im(hrightmenu,"Difference: 6",rmFreqDifference+5, effect.chan==2&&effect.band==5);
im(hrightmenu,"Difference: 5",rmFreqDifference+4, effect.chan==2&&effect.band==4);
im(hrightmenu,"Difference: 4",rmFreqDifference+3, effect.chan==2&&effect.band==3);
im(hrightmenu,"Difference: 3",rmFreqDifference+2, effect.chan==2&&effect.band==2);
im(hrightmenu,"Difference: 2",rmFreqDifference+1, effect.chan==2&&effect.band==1);
im(hrightmenu,"Difference: 1",rmFreqDifference+0, effect.chan==2&&effect.band==0);
im(hrightmenu,"--");
im(hrightmenu,"Right: 6 treble",rmFreqRight+5, effect.chan==1&&effect.band==5);
im(hrightmenu,"Right: 5",rmFreqRight+4, effect.chan==1&&effect.band==4);
im(hrightmenu,"Right: 4",rmFreqRight+3, effect.chan==1&&effect.band==3);
im(hrightmenu,"Right: 3",rmFreqRight+2, effect.chan==1&&effect.band==2);
im(hrightmenu,"Right: 2",rmFreqRight+1, effect.chan==1&&effect.band==1);
im(hrightmenu,"Right: 1 bass",rmFreqRight+0, effect.chan==1&&effect.band==0);
im(hrightmenu,"--");
im(hrightmenu,"Left: 6 treble",rmFreqLeft+5, effect.chan==0&&effect.band==5);
im(hrightmenu,"Left: 5",rmFreqLeft+4, effect.chan==0&&effect.band==4);
im(hrightmenu,"Left: 4",rmFreqLeft+3, effect.chan==0&&effect.band==3);
im(hrightmenu,"Left: 3",rmFreqLeft+2, effect.chan==0&&effect.band==2);
im(hrightmenu,"Left: 2",rmFreqLeft+1, effect.chan==0&&effect.band==1);
im(hrightmenu,"Left: 1 bass",rmFreqLeft+0, effect.chan==0&&effect.band==0);
}
else
{ stk::TColor &col = effect.cols[sel];
string bitmapsel; if (col.type==ctBitmap) bitmapsel=col.bitmap;
im(hrightmenu,"Bitmaps...",rmMoreBitmaps);
for (int bic=0; bic<(int)body->bmps.size(); bic++)
{ string bname = body->bmps[bic].name;
bool checked = (StringLower(bname)==StringLower(bitmapsel));
im(hrightmenu,bname,rmBitmaps+bic,checked,true,true);
}
im(hrightmenu,"--");
im(hrightmenu,"Colours...",rmColMore);
list<COLORREF> cols; if (col.type==ctRGB) cols.push_back(CREF(col.rgb));
im(hrightmenu,cols,col.type!=ctRGB,rmCol,false,&extracols);
im(hrightmenu,"Fade",rmColFade,col.type==ctRGB && col.fadetonext,true,false);
im(hrightmenu,"--");
im(hrightmenu,"Invisible",rmInvisible,col.type==ctNone,true,false);
im(hrightmenu,"--");
if (effect.cols.size()>2) im(hrightmenu,"Delete",rmDelete);
im(hrightmenu,"Add After",rmAddAfter);
im(hrightmenu,"Add Before",rmAddBefore);
}
POINT pt; pt.x=x; pt.y=y; ClientToScreen(hwnd,&pt);
BalanceMenu(hrightmenu);
int cmd=TrackPopupMenu(hrightmenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,hwnd,NULL);
DestroyMenu(hrightmenu);
if (cmd==rmFreqCumMore) editor->UserCumulatives(hwnd);
else if (cmd>=rmFreqCumFirst && cmd<=rmFreqCumLast)
{ double d=retcums[cmd-rmFreqCumFirst].d;
int r=retcums[cmd-rmFreqCumFirst].r;
if (d==0) effect.cumulative=false;
else {effect.cumulative=true; effect.cumrate=d; effect.creflect=r;}
}
else if (cmd==rmFreqNegative) {effect.negative=!effect.negative;}
else if (cmd>=rmFreqDifference && cmd<rmFreqDifference+6) {effect.chan=2; effect.band=cmd-rmFreqDifference;}
else if (cmd>=rmFreqRight && cmd<rmFreqRight+6) {effect.chan=1; effect.band=cmd-rmFreqRight;}
else if (cmd>=rmFreqLeft && cmd<rmFreqLeft+6) {effect.chan=0; effect.band=cmd-rmFreqLeft;}
else if (cmd>=rmFreqKaraoke && cmd<rmFreqKaraoke+6) {effect.chan=3; effect.band=cmd-rmFreqKaraoke;}
else if (cmd==rmMoreBitmaps) editor->Bitmaps(GetParent(hwnd));
else if (cmd>=rmBitmaps && cmd<rmBitmaps+50) {effect.cols[sel].type=ctBitmap; effect.cols[sel].bitmap=body->bmps[cmd-rmBitmaps].name; effect.cols[sel].bindex=-1;}
else if (cmd==rmColMore) editor->UserColours(GetParent(hwnd));
else if (cmd==rmColFade) {effect.cols[sel].type=ctRGB; effect.cols[sel].fadetonext=!effect.cols[sel].fadetonext;}
else if (cmd>=rmCol && cmd<rmCol+50)
{ int r,g,b, c=cmd-rmCol;
if (c<ncols) {r=defcols[c].r; g=defcols[c].g; b=defcols[c].b;}
else if (c<ncols+(int)usercols.size())
{ int ci=ncols; list<TUserColour>::const_iterator ui=usercols.begin();
while (ci<c) {ci++; ui++;}
r=ui->c.r; g=ui->c.g; b=ui->c.b;
}
else
{ int e=c-ncols-(int)usercols.size(); COLORREF cl=extracols[e];
r=GetRValue(cl); g=GetGValue(cl); b=GetBValue(cl);
}
effect.cols[sel].type=ctRGB; effect.cols[sel].rgb=RGBCOLOR(r,g,b);
}
else if (cmd==rmInvisible)
{ effect.cols[sel].type=ctNone;
}
else if (cmd==rmDelete)
{ double f=effect.fracs[sel];
if (sel==0) effect.fracs[sel+1]+=f; else effect.fracs[sel-1]+=f;
vector<stk::TColor>::iterator ci=effect.cols.begin()+sel; effect.cols.erase(ci);
vector<double>::iterator fi=effect.fracs.begin()+sel; effect.fracs.erase(fi);
}
else if (cmd==rmAddBefore || cmd==rmAddAfter)
{ stk::TColor c; c.type=ctRGB; c.rgb=RGBCOLOR(rand()%255,rand()%255,rand()%255); c.fadetonext=true;
double f=effect.fracs[sel]/2;
effect.fracs[sel]=f;
if (cmd==rmAddBefore) {effect.cols.insert(effect.cols.begin()+sel,c); effect.fracs.insert(effect.fracs.begin()+sel,f);}
else if (sel<(int)effect.cols.size()-1) {effect.cols.insert(effect.cols.begin()+sel+1,c); effect.fracs.insert(effect.fracs.begin()+sel+1,f);}
else {effect.cols.push_back(c); effect.fracs.push_back(f);}
}
InvalidateRect(hwnd,NULL,TRUE);
} return 0;
case WM_MOUSEMOVE:
{ if (dat->dragging==-2) return TRUE;
int x=LOWORD(lParam);
double f = ((double)(x-dat->rc.left))/((double)(dat->rc.right-dat->rc.left));
if (f<0) f=0; if (f>1) f=1;
if (dat->dragging==-1) {dat->knobx=dat->rc.left+(int)(f*(double)(dat->rc.right-dat->rc.left)); effect.f=f; InvalidateRect(hwnd,NULL,TRUE); return TRUE;}
double tot=0; for (int segment=0; segment<dat->dragging; segment++) tot+=effect.fracs[segment];
if (f-tot<0.01) return TRUE;
double nextf=tot+effect.fracs[dat->dragging]+effect.fracs[dat->dragging+1];
if (dat->dragging==(int)effect.cols.size()-2) nextf=1;
if (nextf-f<0.01) return TRUE;
effect.fracs[dat->dragging]=f-tot; effect.fracs[dat->dragging+1]=nextf-f;
InvalidateRect(hwnd,NULL,TRUE);
} return TRUE;
case WM_LBUTTONUP:
{ dat->dragging=-2;
} return TRUE;
}
return DefWindowProc(hwnd,msg,wParam,lParam);
}
string TEditor::EffectClick(HWND hpar,const string oldname)
{ //
enum {smDelete=1, smRename=2, smAdd=3, smEdit=4};
HMENU heffectmenu=CreatePopupMenu();
// effects
im(heffectmenu,"Add",smAdd);
if (oldname!="")
{ im(heffectmenu,"Delete",smDelete);
im(heffectmenu,"Rename",smRename);
im(heffectmenu,"Edit",smEdit);
}
//
POINT pt; GetCursorPos(&pt);
int cmd=TrackPopupMenu(heffectmenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,hpar,NULL);
DestroyMenu(heffectmenu);
if (cmd==0) return oldname;
//
MarkUndo();
ismodified=true;
if (cmd==smAdd)
{ string name=CleanEffectName("NewEffect");
TEffect e; e.name=name; e.chan=nextchan; e.band=nextband;
e.negative=false; e.cumulative=false; e.cumrate=1; e.f=0.3;
if (e.chan>2) e.chan=0; // we don't want a special channel. just left/right/diff.
stk::TColor c; c.type=ctRGB; c.rgb=RGBCOLOR(rand()%255,rand()%255,rand()%255); c.fadetonext=true; e.cols.push_back(c); e.fracs.push_back(0.4);
c.rgb=RGBCOLOR(rand()%255,rand()%255,rand()%255); e.cols.push_back(c); e.fracs.push_back(0.6);
body->effects.push_back(e);
return name;
}
// otherwise, manipulate an existing one
vector<TEffect>::iterator effectiterator=get_effect(body->effects,oldname);
if (effectiterator==body->effects.end()) return oldname;
//
if (cmd==smEdit)
{ return "*"+oldname;
}
else if (cmd==smRename || cmd==smDelete)
{ string lcoldname=StringLower(oldname), newname="";
if (cmd==smRename)
{ char c[100]; strcpy(c,oldname.c_str());
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_RENAME),hpar,RenameDlgProc,(LPARAM)c);
if (res!=IDOK || oldname==c) return oldname;
newname=CleanEffectName(c);
}
// remove this effect from any limb/shapebrush/shapeline/style that refers to it:
for (int i=0; i<body->nlimbs; i++)
{ if (StringLower(body->limbs[i].color.effect)==lcoldname)
{ body->limbs[i].linestyle=newname;
if (cmd==smDelete && body->limbs[i].type==ctEffect) body->limbs[i].type=ctNone;
}
}
for (vector<stk::TShape>::iterator si=body->shapes.begin(); si!=body->shapes.end(); si++)
{ if (StringLower(si->brush.effect)==lcoldname)
{ si->brush.effect=newname;
if (cmd==smDelete && si->brush.type==ctEffect) si->brush.type=ctNone;
}
if (StringLower(si->line.effect)==lcoldname)
{ si->line.effect=newname;
if (cmd==smDelete && si->line.type==ctEffect) si->line.type=ctNone;
}
}
for (list<TStyle>::iterator si=body->styles.begin(); si!=body->styles.end(); si++)
{ if (StringLower(si->limb.color.effect)==lcoldname)
{ si->limb.color.effect=newname;
if (cmd==smDelete && si->limb.color.type==ctEffect) si->limb.color.type=ctNone;
}
if (StringLower(si->shape.brush.effect)==lcoldname)
{ si->shape.brush.effect=newname;
if (cmd==smDelete && si->shape.brush.type==ctEffect) si->shape.brush.type=ctNone;
}
}
//
effectiterator->name=newname; if (cmd==smDelete) body->effects.erase(effectiterator);
return newname;
}
//
return oldname;
}
string TEditor::CleanEffectName(const string s)
{ string broot=s;
for (int i=0; i<(int)broot.size(); i++)
{ if (broot[i]==')') broot[i]=']';
if (broot[i]=='(') broot[i]='[';
if (broot[i]=='=') broot[i]='-';
}
for (int i=1; ; i++)
{ string bname;
if (i==1) bname=broot; else bname=broot+StringInt(i);
bool okay=true;
for (vector<TEffect>::const_iterator si=body->effects.begin(); si!=body->effects.end() && okay; si++)
{ if (StringLower(si->name)==StringLower(bname)) okay=false;
}
if (okay) return bname;
}
}
int WINAPI EffectsDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ EffectsDlgData *dat;
#pragma warning( push )
#pragma warning( disable : 4244 4312 )
if (msg==WM_INITDIALOG) {SetWindowLongPtr(hdlg,DWLP_USER,lParam); dat=(EffectsDlgData*)lParam;}
else {dat=(EffectsDlgData*)GetWindowLongPtr(hdlg,DWLP_USER);}
#pragma warning( pop )
if (dat==NULL) return FALSE;
TEditor *editor = dat->editor;
TBody *body = editor->body;
//
switch (msg)
{ case WM_INITDIALOG:
{ // subclass the listbox
HWND hlb = GetDlgItem(hdlg,IDC_LIST);
LONG_PTR oldproc = GetWindowLongPtr(hlb,GWLP_WNDPROC);
SetWindowLongPtr(hdlg,GWLP_USERDATA,oldproc);
SetWindowLongPtr(hlb,GWLP_WNDPROC,(LONG_PTR)ListSubclassProc);
SendMessage(hdlg,WM_APP,0,0);
dat->timeStart=GetTickCount(); dat->timePrev=dat->timeStart; dat->samplei=rand()%3;
SetTimer(hdlg,1,100,NULL);
} return TRUE;
case WM_APP: // reset the contents of the list box. lParam is the one to highlight
{ const char *csel = (const char*)lParam;
SendDlgItemMessage(hdlg,IDC_LIST,LB_RESETCONTENT,0,0);
for (vector<TEffect>::const_iterator si=body->effects.begin(); si!=body->effects.end(); si++)
{ string s = si->tostring();
SendDlgItemMessage(hdlg,IDC_LIST,LB_ADDSTRING,0,(LPARAM)s.c_str());
}
if (body->effects.size()>0)
{ int seli=0;
if (csel!=0) seli=SendDlgItemMessage(hdlg,IDC_LIST,LB_FINDSTRING,(WPARAM)-1,(LPARAM)(string(csel)+"=").c_str());
SendDlgItemMessage(hdlg,IDC_LIST,LB_SETCURSEL,seli,0);
}
} return TRUE;
case WM_TIMER:
{ if (dat->editup) return TRUE;
int seli=SendDlgItemMessage(hdlg,IDC_LIST,LB_GETCURSEL,0,0); if (seli==LB_ERR) return TRUE;
int len = SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXTLEN,seli,0);
char *c=new char[len+1]; SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXT,seli,(LPARAM)c);
char *eq=strchr(c,'='); if (eq!=0) *eq=0;
vector<TEffect>::iterator ei=get_effect(body->effects,c); delete[] c;
if (ei==body->effects.end()) return TRUE;
TEffect &effect = *ei;
//
unsigned int nowt=GetTickCount();
unsigned int time=nowt-dat->timeStart;
unsigned int diff=nowt-dat->timePrev; dat->timePrev=nowt;
double cmul = ((double)diff)/10.0;
//
unsigned int off = (time/41)%samplesize[dat->samplei];
unsigned char *sd = sampledat[dat->samplei]+off*12;
unsigned char s = sd[effect.chan*6+effect.band];
double f = ((double)s)/255.0;
if (effect.chan==2) f-=0.5; // difference channel, has bias
if (effect.cumulative)
{ int dir=1; if (effect.negative) dir*=-1; if (effect.creflect<0) dir*=-1;
double cf=effect.cumrate*f*cmul; if (effect.cumrate<0) cf=-effect.cumrate*cmul;
effect.f += dir*0.01*cf;
if (effect.creflect==0)
{ while (effect.f<0) effect.f+=1; while (effect.f>1) effect.f-=1;
}
else
{ for (;;)
{ if (effect.f>1) {effect.f=2-effect.f; effect.creflect*=-1;}
else if (effect.f<0) {effect.f=-effect.f; effect.creflect*=-1;}
else break;
}
}
}
else
{ if (effect.negative) effect.f=1-f;
else effect.f=f;
}
//
double tot=0; unsigned int segment;
for (segment=0; segment<effect.cols.size()-1; segment++)
{ if (effect.f<tot+effect.fracs[segment]) break;
tot+=effect.fracs[segment];
}
double nexttot=tot+effect.fracs[segment]; if (segment==effect.cols.size()-1) nexttot=1;
stk::TColor col = effect.cols[segment];
stk::TColor nextcol = effect.cols[(segment+1)%effect.cols.size()];
//
RECT rc; GetWindowRect(GetDlgItem(hdlg,IDC_EFFECT),&rc);
ScreenToClient(hdlg,(POINT*)&rc.left); ScreenToClient(hdlg,(POINT*)&rc.right);
HDC hdc=GetDC(hdlg);
if (col.type==ctNone || col.type==ctBitmap) FillRect(hdc,&rc,(HBRUSH)GetStockObject(BLACK_BRUSH));
else if (col.type==ctRGB)
{ LOGBRUSH lbr; lbr.lbStyle=BS_SOLID; lbr.lbColor=RGB(col.rgb.r,col.rgb.g,col.rgb.b);
if (col.fadetonext && nextcol.type==ctRGB)
{ double r1=col.rgb.r, g1=col.rgb.g, b1=col.rgb.b;
double r2=nextcol.rgb.r, g2=nextcol.rgb.g, b2=nextcol.rgb.b;
double f=(effect.f-tot)/(nexttot-tot);
double r=r1*(1-f)+r2*f, g=g1*(1-f)+g2*f, b=b1*(1-f)+b2*f;
lbr.lbColor=RGB((int)r,(int)g,(int)b);
}
HBRUSH hbr=CreateBrushIndirect(&lbr);
FillRect(hdc,&rc,hbr);
DeleteObject(hbr);
}
else LUASSERTMM("unknown col type");
if (col.type==ctBitmap)
{ HDC tdc = CreateCompatibleDC(hdc);
const TBmp &bitmap = body->bmps[col.bindex];
BITMAP bmp; GetObject(bitmap.hbm,sizeof(bmp),&bmp); int bwidth=bmp.bmWidth, bheight=bmp.bmHeight;
SetStretchBltMode(hdc,COLORONCOLOR);
int x,y,w,h;
double fb=((double)bwidth)/((double)bheight), fr=((double)(rc.right-rc.left))/((double)(rc.bottom-rc.top));
if (fb>fr)
{ x=rc.left; w=rc.right-rc.left;
double f = ((double)w)/((double)bwidth);
h=(int)(bheight*f);
y=rc.top + (rc.bottom-rc.top-h)/2;
}
else
{ y=rc.top; h=rc.bottom-rc.top;
double f = ((double)h)/((double)bheight);
w=(int)(bwidth*f);
x=rc.left + (rc.right-rc.left-w)/2;
}
// do it with the mask
HGDIOBJ hold;
if (bitmap.hbmask!=0)
{ hold = SelectObject(tdc,bitmap.hbmask);
StretchBlt(hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCAND);
SelectObject(tdc,bitmap.hbm);
StretchBlt(hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCPAINT);
}
else
{ hold = SelectObject(tdc,bitmap.hbm);
StretchBlt(hdc,x,y,w,h,tdc,0,0,bwidth,bheight,SRCCOPY);
}
SelectObject(tdc,hold);
DeleteDC(tdc);
}
double dx=effect.f*(double)(rc.right-rc.left-8);
int x=rc.left+(int)dx;
rc.left=x-4; rc.right=x+4; rc.top=rc.bottom-8;
FillRect(hdc,&rc,(HBRUSH)GetStockObject(WHITE_BRUSH));
rc.left=x-2; rc.right=x+2; rc.top+=2; rc.bottom-=2;
FillRect(hdc,&rc,(HBRUSH)GetStockObject(BLACK_BRUSH));
ReleaseDC(hdlg,hdc);
} return TRUE;
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (id==IDCANCEL) EndDialog(hdlg,id);
else if (id==IDOK)
{ if (dat->editup)
{ ShowWindow(GetDlgItem(hdlg,IDC_LIST),SW_SHOW);
ShowWindow(GetDlgItem(hdlg,IDC_LIST1),SW_SHOW);
ShowWindow(GetDlgItem(hdlg,IDC_LIST2),SW_SHOW);
ShowWindow(GetDlgItem(hdlg,IDC_EDIT1),SW_HIDE);
ShowWindow(GetDlgItem(hdlg,IDC_EDIT2),SW_HIDE);
SetWindowText(GetDlgItem(hdlg,IDOK),"Close");
HWND hc = FindWindowEx(hdlg,0,"EffectsClass",NULL);
if (hc!=0) SendMessage(hc,WM_COMMAND,IDOK,0);
string newdef=dat->seffect; int pos=newdef.find("=");
string newname; if (pos!=-1) newname=newdef.substr(0,pos);
vector<TEffect>::iterator ei=get_effect(body->effects,newname);
if (ei!=body->effects.end()) ei->fromstring(newdef);
SendMessage(hdlg,WM_APP,0,(LPARAM)newname.c_str());
MakeBindexes(body); MakeEindexes(body);
editor->Recalc(0);
dat->editup=false;
}
else EndDialog(hdlg,id);
}
else if (id==IDC_LIST && code==BN_CLICKED)
{ int seli = SendDlgItemMessage(hdlg,IDC_LIST,LB_GETCURSEL,0,0);
string oldname="", olddef="";
if (seli!=LB_ERR)
{ int len = SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXTLEN,seli,0);
char *c=new char[len+1]; SendDlgItemMessage(hdlg,IDC_LIST,LB_GETTEXT,seli,(LPARAM)c);
dat->seffect=c; char *eq=strchr(c,'='); if (eq!=0) *eq=0;
oldname=c; delete[] c;
}
const string newname = editor->EffectClick(hdlg,oldname);
bool edit=false;
if (newname.length()>0 && newname[0]=='*') edit=true;
if (!edit) {SendMessage(hdlg,WM_APP,0,(LPARAM)newname.c_str()); return TRUE;}
dat->editup=true;
WNDCLASSEX wcex; ZeroMemory(&wcex,sizeof(wcex)); wcex.cbSize = sizeof(WNDCLASSEX);
BOOL res=GetClassInfoEx(hInstance,"EffectsClass",&wcex);
if (!res)
{ wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)EffectWndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.lpszClassName = "EffectsClass";
ATOM res=RegisterClassEx(&wcex);
LUASSERT(res!=0);
}
RECT rc; GetWindowRect(GetDlgItem(hdlg,IDC_LIST),&rc); ScreenToClient(hdlg,(POINT*)&rc.left); int x=rc.left,y=rc.top;
GetWindowRect(GetDlgItem(hdlg,IDC_EFFECT),&rc); ScreenToClient(hdlg,(POINT*)&rc.right); int w=rc.right-x,h=rc.bottom-y;
CreateWindow("EffectsClass","",WS_CHILD|WS_VISIBLE,x,y,w,h,hdlg,0,hInstance,dat);
ShowWindow(GetDlgItem(hdlg,IDC_LIST),SW_HIDE);
ShowWindow(GetDlgItem(hdlg,IDC_LIST1),SW_HIDE);
ShowWindow(GetDlgItem(hdlg,IDC_LIST2),SW_HIDE);
ShowWindow(GetDlgItem(hdlg,IDC_EDIT1),SW_SHOW);
ShowWindow(GetDlgItem(hdlg,IDC_EDIT2),SW_SHOW);
SetWindowText(GetDlgItem(hdlg,IDOK),"OK");
}
} return TRUE;
case WM_DESTROY:
{ KillTimer(hdlg,1);
} return TRUE;
}
return FALSE;
}
void TEditor::Effects(HWND hpar)
{ EffectsDlgData dat;
dat.editor=this;
DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_EFFECTS),hpar,EffectsDlgProc,(LPARAM)&dat);
}
void TEditor::Category()
{ char c[MAX_PATH]; strcpy(c,body->category.c_str());
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_RENAME),mhwnd,RenameDlgProc,(LPARAM)c);
if (res!=IDOK) return;
string newcat = string(c);
if (newcat==body->category) return;
MarkUndo();
body->category = newcat;
ismodified=true;
}
void TEditor::TargetFramerate()
{ char c[MAX_PATH]; wsprintf(c,"%i",body->fps);
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_RENAME),mhwnd,RenameDlgProc,(LPARAM)c);
if (res!=IDOK) return;
int newfps; res=sscanf(c,"%i",&newfps);
if (res!=1 || newfps<1) {MessageBeep(0); return;}
if (newfps==body->fps) return;
MarkUndo();
body->fps = newfps;
ismodified=true;
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
bool FileExists(const string fn)
{ HANDLE hFile=CreateFile(fn.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
if (hFile==INVALID_HANDLE_VALUE) return FALSE;
CloseHandle(hFile); return TRUE;
}
bool AreFilenamesSame(const string fa,const string fb)
{ if (StringLower(fa)==StringLower(fb)) return true;
HANDLE hfa = CreateFile(fa.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
HANDLE hfb = CreateFile(fb.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
BY_HANDLE_FILE_INFORMATION fia,fib;
GetFileInformationByHandle(hfa,&fia);
GetFileInformationByHandle(hfb,&fib);
if (hfa!=INVALID_HANDLE_VALUE) CloseHandle(hfa);
if (hfb!=INVALID_HANDLE_VALUE) CloseHandle(hfb);
if (hfa==INVALID_HANDLE_VALUE || hfb==INVALID_HANDLE_VALUE) return false;
bool same = (fia.nFileIndexHigh==fib.nFileIndexHigh);
same &= (fia.nFileIndexLow ==fib.nFileIndexLow);
return same;
}
bool IsFileWithinDirectory(const string afn,const string adir)
{ string fn=StringLower(afn), dir=StringLower(adir);
if (fn.find(dir)==0) return true;
// maybe I should do something more sophisticated in case fn is a \\\network path
// but dir is just a c:\normal\path,
// or in case one of them is a short filename and the other is not.
return false;
// ... but I can't be bothered
}
void SelectAsDefault(const string fn)
{ vector<TPre> pre; DirScan(pre,GetStickDir()+"\\");
string s = StringLower(ExtractFileName(fn));
int preset=-1;
for (int i=0; i<(int)pre.size(); i++)
{ string ps = StringLower(pre[i].path);
if (ps.find(s)!=string::npos) preset=i+1;
}
if (preset==-1) return;
HKEY hkey; DWORD disp; LONG res = RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Lu\\Sticky",0,NULL,0,KEY_WRITE,NULL,&hkey,&disp);
if (res!=ERROR_SUCCESS) return;
char pr[200]; wsprintf(pr,"%i",(int)preset);
RegSetValueEx(hkey,"preset",0,REG_SZ,(LPBYTE)pr,(DWORD)strlen(pr)+1);
RegCloseKey(hkey);
}
/*
// We used to remove duplicates. But this is a bad place to do it.
//
void FixUpRedundancy(HWND hwnd)
{ // first, check whether it's already been fixed up
bool dealtwith=false;
HKEY key; LONG res=RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Lu\\Sticky",0,KEY_READ,&key);
if (res==ERROR_SUCCESS)
{ DWORD dat, type, size=sizeof(dat);
res=RegQueryValueEx(key,"DealtWithRedundancy3.4",NULL,&type,(LPBYTE)&dat,&size);
if (res==ERROR_SUCCESS) dealtwith=true;
RegCloseKey(key);
}
if (dealtwith) return;
// did we encounter any redundancy?
vector<TPre> pre; DirScan(pre,GetStickDir()+"\\");
const char *oss[] = {"amb bars","demented tweety-pie","droopy nose thing","jumping numbers",
"fireworks (robert henderson)","jumping numbers","pac man","sound echoes",
"whirls","windows","belly dancer","breakdancing lobster","dancer (vale)",
"dancing stick guy (justin)","disco (mwstumpy)","girly goth dancer (midnight)",
"riverdancer (midnight)","walk like an egyptian","bot head full (heppler)",
"genie (evil boris)","johnny5 (evil boris)","lamp","snowman (jkabodnar)","spider (vale)",
"band (marius kolesky)","bunny love (heppler)","bunny rock (manifest deity)",
"drum (marius kolesky)","drummer2 (dod)","drummer (sneaky sneaks)","evil guitarist (lethal hairdo)",
"rock guitarist (lim sh)","rocker (evil boris)","alberto (rk-pace)"};
int nos=sizeof(oss)/sizeof(char*);
vector<int> olds,news; olds.resize(nos); news.resize(nos); for (int i=0; i<nos; i++) {olds[i]=-1; news[i]=-1;}
bool anyredundancy=false;
for (int i=0; i<(int)pre.size(); i++)
{ string s = StringLower(pre[i].desc);
const char *entry = s.c_str();
for (int j=0; j<nos; j++)
{ const char *c = strstr(entry,oss[j]);
if (c==entry) olds[j]=i; else if (c!=0) news[j]=i;
if (olds[j]!=-1 && news[j]!=-1) anyredundancy=true;
}
}
// shall we remove them?
if (anyredundancy)
{ int ires=MessageBox(hwnd,"Since upgrading, there are =a few duplicate stick figures.\r\n"
"Shall I tidy them up now?\r\n\r\n"
"(This won't take long, and will only happen once.)","Duplicate stick figures",MB_YESNOCANCEL);
if (ires!=IDYES) return;
}
// we're here either because there was no redundany, or because there was and we've
// decided to tidy it up. In either case, we can write to the log.
DWORD disp; res=RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Lu\\Sticky",0,NULL,0,KEY_WRITE,NULL,&key,&disp);
if (res==ERROR_SUCCESS)
{ DWORD dat=1; RegSetValueEx(key,"DealtWithRedundancy3.4",0,REG_DWORD,(LPBYTE)&dat,sizeof(dat));
RegCloseKey(key);
}
if (!anyredundancy) return;
//
// Our tidying subsists in this: for any duplicates, we check that they've got
// identical file sizes, and if so we move the old one into an 'old' directory.
string savedir=GetStickDir(); // "c:\\program files\\stick figures\\sticks"
savedir=ExtractFilePath(savedir); // "c:\\program files\\stick figures"
savedir=savedir+"\\duplicate sticks (can be deleted)";
bool donesavedir=false;
//
for (int i=0; i<nos; i++)
{ if (olds[i]!=-1 && news[i]!=-1)
{ int jo=olds[i], jn=news[i];
string desc = pre[jo].desc;
string ofn = pre[jo].path;
string nfn = pre[jn].path;
string sfn = savedir+"\\"+ExtractFileName(ofn);
HANDLE hofn=CreateFile(ofn.c_str(),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
HANDLE hnfn=CreateFile(nfn.c_str(),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
DWORD sizeo=0,sizen=0;
if (hofn!=INVALID_HANDLE_VALUE) sizeo=GetFileSize(hofn,NULL);
if (hnfn!=INVALID_HANDLE_VALUE) sizen=GetFileSize(hnfn,NULL);
if (hofn!=INVALID_HANDLE_VALUE) CloseHandle(hofn);
if (hnfn!=INVALID_HANDLE_VALUE) CloseHandle(hnfn);
bool aresame = (sizeo==sizen && sizeo!=0 && sizen!=0);
if (aresame)
{ if (!donesavedir) CreateDirectory(savedir.c_str(),NULL); donesavedir=true;
MoveFileEx(ofn.c_str(),sfn.c_str(),MOVEFILE_COPY_ALLOWED);
}
}
}
}
*/
class TInstallItemInfo
{ public:
bool operator<(const TInstallItemInfo &b) const {return _stricmp(desc.c_str(),b.desc.c_str())<0;}
string category, name, desc, fn;
string srcfn; HZIP srczip; int srczi;
};
class TInstallDlgData
{ public:
TInstallDlgData(vector<TInstallItemInfo> *i) : items(i), b(0) {}
~TInstallDlgData() {if (b!=0) delete b; b=0; if (hbm!=0) DeleteObject(hbm); hbm=0;}
vector<TInstallItemInfo> *items;
TBody *b;
unsigned int timeStart,timePrev; int samplei;
RECT prc; HBITMAP hbm;
};
LRESULT CALLBACK KeylessListProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ HWND hpar = GetParent(hwnd); if (hpar==0) return DefWindowProc(hwnd,msg,wParam,lParam);
LONG_PTR oldproc = GetWindowLongPtr(hpar,GWLP_USERDATA); if (oldproc==0) return DefWindowProc(hwnd,msg,wParam,lParam);
switch (msg)
{ case WM_GETDLGCODE:
{ LRESULT code = CallWindowProc((WNDPROC)oldproc,hwnd,msg,wParam,lParam);
code &= ~(DLGC_WANTALLKEYS|DLGC_WANTCHARS|DLGC_WANTMESSAGE);
return code;
}
}
return CallWindowProc((WNDPROC)oldproc,hwnd,msg,wParam,lParam);
}
int WINAPI InstallDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ TInstallDlgData *idd = (TInstallDlgData*)GetWindowLongPtr(hdlg,DWLP_USER);
switch (msg)
{ case WM_INITDIALOG:
{ idd = (TInstallDlgData*)lParam; SetWindowLongPtr(hdlg,DWLP_USER,(LONG_PTR)idd);
idd->timeStart=GetTickCount(); idd->timePrev=idd->timeStart;
idd->samplei=rand()%3;
unsigned int maxtime = (samplesize[idd->samplei]/12)*40; idd->timeStart -= rand()%maxtime;
RECT rc; GetWindowRect(hdlg,&rc);
int w=rc.right-rc.left, h=rc.bottom-rc.top;
int cx=GetSystemMetrics(SM_CXSCREEN)/2, cy=GetSystemMetrics(SM_CYSCREEN)/2;
MoveWindow(hdlg,cx-w/2,cy-h/2,w,h,FALSE);
GetWindowRect(GetDlgItem(hdlg,IDC_PREVIEW),&idd->prc);
ScreenToClient(hdlg,(POINT*)&idd->prc.left); ScreenToClient(hdlg,(POINT*)&idd->prc.right);
HDC hdc=GetDC(0); idd->hbm=CreateCompatibleBitmap(hdc,w,h); ReleaseDC(0,hdc);
// build the list
bool anyalready=false;
SendDlgItemMessage(hdlg,IDC_LIST,LB_RESETCONTENT,0,0);
for (vector<TInstallItemInfo>::const_iterator i=idd->items->begin(); i!=idd->items->end(); i++)
{ string s = i->desc;
if (FileExists(i->fn)) {s+=" *"; anyalready=true;}
SendDlgItemMessage(hdlg,IDC_LIST,LB_ADDSTRING,0,(LPARAM)s.c_str());
}
// set the text
string s = "Do you wish to install ";
if (idd->items->size()>1) s+="copies of these stick figures?"; else s+="a copy of this stick figure?";
if (anyalready) {s+="\r\n* will overwrite existing version.";}
SetDlgItemText(hdlg,IDC_INSTALLPROMPT,s.c_str());
// subclass the listbox
LONG_PTR oldproc = GetWindowLongPtr(GetDlgItem(hdlg,IDC_LIST),GWLP_WNDPROC);
SetWindowLongPtr(hdlg,GWLP_USERDATA,oldproc);
SetWindowLongPtr(GetDlgItem(hdlg,IDC_LIST),GWLP_WNDPROC,(LONG_PTR)KeylessListProc);
// final touches
SendDlgItemMessage(hdlg,IDC_LIST,LB_SETCURSEL,0,0);
SendMessage(hdlg,WM_COMMAND,(WPARAM)(IDC_LIST|(LBN_SELCHANGE<<16)),0);
SetTimer(hdlg,1,40,NULL);
PostMessage(hdlg,WM_TIMER,1,0);
return TRUE;
}
case WM_TIMER:
{ if (idd->b==0) return TRUE;
unsigned int nowt=GetTickCount();
unsigned int nextt=idd->timePrev+1000/idd->b->fps;
if (nowt<nextt) return TRUE;
//
unsigned int time=nowt-idd->timeStart;
double cmul = ((double)(nowt-idd->timePrev))/10.0;
idd->timePrev=nowt;
//
unsigned int off = (time/41)%samplesize[idd->samplei];
unsigned char *sd = sampledat[idd->samplei]+off*12;
double freq[3][6];
for (int chan=0; chan<2; chan++)
{ for (int band=0; band<6; band++)
{ unsigned char s = sd[chan*6+band];
double d = ((double)s)/255.0;
freq[chan][band]=d;
}
}
freq[2][0]=freq[0][3]; freq[2][1]=freq[1][4];
//
idd->b->AssignFreq(freq,cmul);
idd->b->RecalcEffects(true);
idd->b->Recalc();
InvalidateRect(hdlg,&idd->prc,FALSE);
return TRUE;
}
case WM_PAINT:
{ HDC hdc=GetDC(hdlg);
//
RECT drc; drc.left=0; drc.top=0; drc.right=idd->prc.right-idd->prc.left; drc.bottom=idd->prc.bottom-idd->prc.top;
HDC sdc=GetDC(0), tdc=CreateCompatibleDC(sdc); ReleaseDC(0,sdc);
HGDIOBJ hold=SelectObject(tdc,idd->hbm);
SimpleDraw(tdc,drc,idd->b);
BitBlt(hdc,idd->prc.left,idd->prc.top,idd->prc.right-idd->prc.left,idd->prc.bottom-idd->prc.top,tdc,0,0,SRCCOPY);
SelectObject(tdc,hold); DeleteDC(tdc);
ReleaseDC(hdlg,hdc);
return FALSE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (id==IDC_LIST && code==LBN_SELCHANGE)
{ // load up a stick
int i=SendDlgItemMessage(hdlg,IDC_LIST,LB_GETCURSEL,0,0);
if (i==LB_ERR) return FALSE;
TInstallItemInfo &inf = idd->items->at(i);
char err[1000];
if (idd->b==0) idd->b=new TBody();
if (inf.srcfn!="") LoadBody(&idd->b,inf.srcfn.c_str(),err,lbForUse);
else LoadBodyZip(&idd->b,inf.srczip,inf.srczi,err,lbForUse);
idd->timeStart=GetTickCount();
idd->samplei=rand()%3;
unsigned int maxtime = (samplesize[idd->samplei]/12)*40; idd->timeStart -= rand()%maxtime;
}
if ((id==IDYES || id==IDNO || id==IDCANCEL))
{ if (idd->b!=0) delete idd->b; idd->b=0;
EndDialog(hdlg,id);
}
if (id==IDYES)
{ // copy it
SetCapture(hdlg);
SetCursor(LoadCursor(NULL,IDC_WAIT));
string newdefault="";
for (vector<TInstallItemInfo>::const_iterator i=idd->items->begin(); i!=idd->items->end(); i++)
{ const TInstallItemInfo &inf = *i;
ForceDirectories(ExtractFilePath(inf.fn));
if (inf.srcfn!="") CopyFile(inf.srcfn.c_str(),inf.fn.c_str(),FALSE);
else UnzipItem(inf.srczip,inf.srczi, inf.fn.c_str());
newdefault=i->fn;
}
SelectAsDefault(newdefault);
SetCursor(LoadCursor(NULL,IDC_ARROW));
ReleaseCapture();
}
if ((id==IDYES || id==IDNO))
{ // show the folder
string stickdir=GetStickDir();
ShellExecute(NULL,"open",stickdir.c_str(),NULL,NULL,SW_SHOWNORMAL);
}
return TRUE;
}
case WM_DESTROY:
{ KillTimer(hdlg,1);
return TRUE;
}
}
return FALSE;
}
string CleanWebEscapeChars(const string fn)
{ size_t len=fn.length();
if (len==0) return "";
// get rid of the %20 entries, replacing them with spaces
string s(len,0); const char *c=fn.c_str();
for (size_t i=0; i<len; i++)
{ if (c[0]=='%' && c[1]=='2' && c[2]=='0') {s[i]=' '; c+=3;}
else {s[i]=*c; c++;}
}
// maybe s has the form filename[1].stk or filename[1], in which
// case we remove the number and square brackets
c=s.c_str();
const char *close=strrchr(c,']'), *open=strrchr(c,'[');
if (close!=0 && open!=0 && open<close && (close[1]=='.' || close[1]==0))
{ bool allnums=true;
for (const char *d=open+1; d<close; d++)
{ if (*d<'0' || *d>'9') allnums=false;
}
if (allnums)
{ string t = string(c,open-c);
if (close[1]!=0) t+=string(close+1);
s=t;
}
}
return s;
}
int InstallZipFile(const char *fn,bool *wasjustastick)
{ string stickdir=GetStickDir();
HZIP hz = OpenZip(fn,NULL);
ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numentries=ze.index;
vector<TInstallItemInfo> items;
int numstk=0, numbmp=0, numstyletxt=0, numsticktxt=0, numother=0;
for (int i=0; i<numentries; i++)
{ GetZipItem(hz,i,&ze);
string fn(ze.name);
if (StringLower(ze.name)=="mainstick.txt") {numsticktxt++; continue;}
if (StringLower(ze.name)=="styles.txt") {numstyletxt++; continue;}
if (StringLower(stk::ExtractFileExt(ze.name))==".bmp") {numbmp++; continue;}
if (StringLower(stk::ExtractFileExt(ze.name))!=".stk") {numother++; continue;}
numstk++;
fn=CleanWebEscapeChars(stk::ChangeFileExt(stk::ExtractFileName(ze.name),""));
char buf[1000]; UnzipItem(hz,i,buf,1000); buf[999]=0;
// normally what we've unzipped will be a stick header. But we also
// allow for badly-formed .stk files which lack the header and go
// straight into a zip. (i.e. someone broke their zip-header).
DWORD magic = * ((DWORD*)buf);
bool iszipfile = (magic==0x04034b50);
iszipfile |= (magic==0x5a4b5453);
bool isstickfile = (magic==0x6d696c6e);
if (iszipfile)
{ char *fullbuf = new char[ze.unc_size];
UnzipItem(hz,i,fullbuf,ze.unc_size);
// !!! seems to be a bug here. The file we unzipped was the correct size
// but has the wrong data. Maybe a problem with unzipping a zip that contains a zip.
HZIP hsubz = OpenZip(fullbuf,ze.unc_size,NULL);
if (hsubz!=0)
{ int subi; FindZipItem(hsubz,"mainstick.txt",true,&subi,NULL);
if (subi!=-1)
{ UnzipItem(hsubz,subi,buf,1000); buf[999]=0; isstickfile=true;
}
CloseZip(hsubz);
}
}
if (!isstickfile) continue;
const char *c=strstr(buf,"\ncategory="); string category("");
if (c!=0) {c+=10; while (*c==' ') c++; if (*c==0) c=0;}
if (c!=0)
{ const char *end=c; while (*end!='\r' && *end!='\n' && *end!=0) end++;
while (end>c+1 && end[-1]==' ') end--; category=string(c,end-c);
}
TInstallItemInfo iii;
iii.category=category; iii.name=fn;
if (category=="") iii.desc=fn; else iii.desc=category+"\\"+fn;
iii.fn=stickdir+"\\"+iii.desc+".stk";
iii.srcfn=""; iii.srczip=hz; iii.srczi=i;
items.push_back(iii);
}
if (numstk==0 && numsticktxt>0) {CloseZip(hz); *wasjustastick=true; return IDCANCEL;}
if (items.size()==0) {CloseZip(hz); MessageBox(NULL,"No stick figures found","Sticky",MB_OK); return IDCANCEL;}
sort(items.begin(),items.end());
TInstallDlgData idd(&items);
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_INSTALL),NULL,InstallDlgProc,(LPARAM)&idd);
CloseZip(hz);
return res;
}
typedef struct {string artist, title, filename, regexp, stick;} TMatchData;
typedef struct
{ list<string> recents; vector<TMatchData> cur_recents;
list<TRule> rules; vector<TMatchData> cur_rules;
vector<TPre> *pre;
string re; string stick; bool ignore;
} TAssocDlgData;
string reggarble(const string s,bool emptyiswildcard)
{ if (emptyiswildcard && s=="") return ".*";
string t; size_t len=s.length();
for (size_t i=0; i<len; i++)
{ if (s[i]=='*') t+=".*";
else
{ if (strchr(".+@#()&$|[]{}\\",s[i])!=0) t+="\\";
t+=string(&s[i],1);
}
}
return t;
}
string regungarble(const string s)
{ string t; size_t len=s.length();
for (size_t i=0; i<len; i++)
{ if (s[i]=='.' && i<len-1 && s[i+1]=='*') {i++; t+="*";}
else
{ bool escape = (s[i]=='\\');
if (escape) {if (i==len-1) return ""; else i++;}
bool ctrl = (strchr(".*+@#()&$|[]{}\\",s[i])!=0);
if (escape&&!ctrl) return ""; // regexp had a slash in a way that we didn't create, eg. \n
if (!escape&&ctrl) return ""; // regexp had a ctrl char, which we don't understand
t+=string(&s[i],1);
}
}
return t;
}
string make_standard_re(const string artist, const string title, const string filename)
{ string re = "ARTIST="+reggarble(artist,true)+"___TITLE="+reggarble(title,true)+"___FILENAME="+reggarble(filename,true)+"___";
return re;
}
bool get_standard_re(const string s, string &artist, string &title, string &filename)
{ // we wish to see whether the regexp is in a form we understand
// i.e. ARTIST=pattern___TITLE=pattern___FILENAME=pattern___
const char *c = s.c_str();
REGEXP re; regbegin(&re,"ARTIST=(.*)___TITLE=(.*)___FILENAME=(.*)___",0);
REGMATCH m[4]; bool match = regmatch(&re,c,m,4);
regend(&re);
if (!match) return false;
artist = string(c+m[1].i,m[1].len); artist=regungarble(artist);
title = string(c+m[2].i,m[2].len); title=regungarble(title);
filename = string(c+m[3].i,m[3].len); filename=regungarble(filename);
return (artist!="" && title!="" && filename!="");
}
LRESULT CALLBACK StickSubclassProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ HWND hpar = GetParent(hwnd); if (hpar==0) return DefWindowProc(hwnd,msg,wParam,lParam);
LONG_PTR oldproc = GetWindowLongPtr(hpar,GWLP_USERDATA); if (oldproc==0) return DefWindowProc(hwnd,msg,wParam,lParam);
if (msg==WM_RBUTTONDOWN)
{ SetFocus(hwnd);
int id = GetWindowLongPtr(hwnd,GWLP_ID);
SendMessage(hpar,WM_COMMAND,(WPARAM)(id|(BN_CLICKED<<16)),(LPARAM)hwnd);
return 0;
}
else if (msg==WM_RBUTTONUP) return 0;
return CallWindowProc((WNDPROC)oldproc,hwnd,msg,wParam,lParam);
}
int WINAPI RuleDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ TAssocDlgData *add = (TAssocDlgData*)GetWindowLongPtr(hdlg,DWLP_USER);
switch (msg)
{ case WM_INITDIALOG:
{ add = (TAssocDlgData*)lParam; SetWindowLongPtr(hdlg,DWLP_USER,(LONG_PTR)add);
add->ignore=false;
SetDlgItemText(hdlg,IDC_REGEXP,add->re.c_str());
SetDlgItemText(hdlg,IDC_STICKRE,add->stick.c_str());
// subclass the stick edit box
HWND hstick = GetDlgItem(hdlg,IDC_STICK);
LONG_PTR oldproc = GetWindowLongPtr(hstick,GWLP_WNDPROC);
SetWindowLongPtr(hdlg,GWLP_USERDATA,oldproc);
SetWindowLongPtr(hstick,GWLP_WNDPROC,(LONG_PTR)StickSubclassProc);
return TRUE;
}
case WM_APP+1: // deduce regexp from fields
{ char c[5000];
GetDlgItemText(hdlg,IDC_ARTIST,c,5000); string artist(c);
GetDlgItemText(hdlg,IDC_TITLE,c,5000); string title(c);
GetDlgItemText(hdlg,IDC_FILENAME,c,5000); string filename(c);
string re = make_standard_re(artist,title,filename);
GetDlgItemText(hdlg,IDC_STICK,c,5000);
string sre = reggarble(c);
add->ignore=true;
SetDlgItemText(hdlg,IDC_REGEXP,re.c_str());
SetDlgItemText(hdlg,IDC_STICKRE,sre.c_str());
add->ignore=false;
return TRUE;
}
case WM_APP: // deduce fields from regexp
{ char c[5000]; GetDlgItemText(hdlg,IDC_REGEXP,c,5000);
string artist, title, filename;
bool stdform = get_standard_re(c,artist,title,filename);
GetDlgItemText(hdlg,IDC_STICKRE,c,5000);
string stick = regungarble(c);
add->ignore=true;
SetDlgItemText(hdlg,IDC_ARTIST,stdform?artist.c_str():"");
SetDlgItemText(hdlg,IDC_TITLE,stdform?title.c_str():"");
SetDlgItemText(hdlg,IDC_FILENAME,stdform?filename.c_str():"");
SetDlgItemText(hdlg,IDC_STICK,stick.c_str());
add->ignore=false;
EnableWindow(GetDlgItem(hdlg,IDC_ARTIST),stdform);
EnableWindow(GetDlgItem(hdlg,IDC_TITLE),stdform);
EnableWindow(GetDlgItem(hdlg,IDC_FILENAME),stdform);
EnableWindow(GetDlgItem(hdlg,IDC_STICK),stick!="");
return TRUE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (!add->ignore && (id==IDC_STICK||id==IDC_ARTIST||id==IDC_TITLE||id==IDC_FILENAME)&&code==EN_CHANGE) SendMessage(hdlg,WM_APP+1,0,0);
if (!add->ignore && (id==IDC_REGEXP||id==IDC_STICKRE) && code==EN_CHANGE) SendMessage(hdlg,WM_APP,0,0);
if (id==IDC_HELPBTN && code==BN_CLICKED)
{ string hlp = GetStickDir()+"\\associate sticks with music.stam";
string cmd = "notepad.exe \""+hlp+"\"";
STARTUPINFO si; ZeroMemory(&si,sizeof(si)); si.cb=sizeof(si);
PROCESS_INFORMATION pi; ZeroMemory(&pi,sizeof(pi));
BOOL res = CreateProcess(NULL,(char*)cmd.c_str(),NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);
if (res) {CloseHandle(pi.hProcess); CloseHandle(pi.hThread);}
else MessageBeep(0);
}
if (id==IDC_STICK && code==BN_CLICKED)
{ if (add->pre->size()==0)
{ SetCapture(hdlg); SetCursor(LoadCursor(NULL,IDC_WAIT));
DirScan(*(add->pre),GetStickDir()+"\\",true);
SetCursor(LoadCursor(NULL,IDC_ARROW)); ReleaseCapture();
}
HMENU hmenu=CreatePopupMenu();
for (int i=add->pre->size()-1; i>=0; i--)
{ string s = add->pre->at(i).desc;
PopulateMenu(hmenu,s.c_str(),1000+i,false);
}
POINT pt; GetCursorPos(&pt); RECT rc; GetWindowRect(GetDlgItem(hdlg,IDC_STICK),&rc);
if (pt.x<rc.left) pt.x=rc.left; if (pt.x>rc.right) pt.x=rc.right;
if (pt.y<rc.top) pt.y=rc.top; if (pt.y>rc.bottom) pt.y=rc.bottom;
int cmd=TrackPopupMenu(hmenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD,pt.x,pt.y,0,hdlg,NULL);
DestroyMenu(hmenu);
if (cmd>=1000)
{ string stick = add->pre->at(cmd-1000).regexp;
SetDlgItemText(hdlg,IDC_STICK,stick.c_str());
}
}
if (id==IDOK)
{ char c[5000]; REGEXP re;
GetDlgItemText(hdlg,IDC_REGEXP,c,5000); string match(c);
GetDlgItemText(hdlg,IDC_STICKRE,c,5000); string stickre(c);
bool matchok = regbegin(&re,match.c_str(),0); regend(&re);
bool stickok = regbegin(&re,stickre.c_str(),0); regend(&re);
if (!matchok || !stickok)
{ MessageBox(hdlg,"Not a valid regular-expression","Error",MB_OK);
SendDlgItemMessage(hdlg,matchok?IDC_STICKRE:IDC_REGEXP,EM_SETSEL,0,(LPARAM)-1);
SetFocus(GetDlgItem(hdlg,matchok?IDC_STICKRE:IDC_REGEXP));
}
else
{ add->re = match;
add->stick = stickre;
EndDialog(hdlg,IDOK);
}
}
if (id==IDCANCEL) EndDialog(hdlg,IDCANCEL);
return TRUE;
}
}
return FALSE;
}
LRESULT CALLBACK DellistSubclassProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ HWND hpar = GetParent(hwnd); if (hpar==0) return DefWindowProc(hwnd,msg,wParam,lParam);
LONG_PTR oldproc = GetWindowLongPtr(hpar,GWLP_USERDATA); if (oldproc==0) return DefWindowProc(hwnd,msg,wParam,lParam);
if (msg==WM_KEYDOWN && (wParam==VK_DELETE || wParam==VK_BACK))
{ SendMessage(hpar,WM_COMMAND,(WPARAM)(IDC_REMOVE|(BN_CLICKED<<16)),0);
}
return CallWindowProc((WNDPROC)oldproc,hwnd,msg,wParam,lParam);
}
int WINAPI AssocDlgProc(HWND hdlg,UINT msg,WPARAM wParam,LPARAM lParam)
{ TAssocDlgData *add = (TAssocDlgData*)GetWindowLongPtr(hdlg,DWLP_USER);
switch (msg)
{ case WM_INITDIALOG:
{ add = (TAssocDlgData*)lParam; SetWindowLongPtr(hdlg,DWLP_USER,(LONG_PTR)add);
RECT rc; GetWindowRect(hdlg,&rc); int w=rc.right-rc.left, h=rc.bottom-rc.top;
int cx=GetSystemMetrics(SM_CXSCREEN)/2, cy=GetSystemMetrics(SM_CYSCREEN)/2;
MoveWindow(hdlg,cx-w/2,cy-h/2,w,h,FALSE);
SendMessage(hdlg,WM_APP,0,0); // recents
SendMessage(hdlg,WM_APP+1,0,0); // rules
SendDlgItemMessage(hdlg,IDC_RULES,LB_SETCURSEL,(WPARAM)-1,0);
SendDlgItemMessage(hdlg,IDC_RECENTS,LB_SETCURSEL,(WPARAM)-1,0);
SendMessage(hdlg,WM_COMMAND,(WPARAM)(IDC_RULES|(LBN_SELCHANGE<<16)),0); // enable buttons
// subclass the rules listbox
HWND hlb = GetDlgItem(hdlg,IDC_RULES);
LONG_PTR oldproc = GetWindowLongPtr(hlb,GWLP_WNDPROC);
SetWindowLongPtr(hdlg,GWLP_USERDATA,oldproc);
SetWindowLongPtr(hlb,GWLP_WNDPROC,(LONG_PTR)DellistSubclassProc);
return TRUE;
}
case WM_APP+1: // populate the "rules" box
{ HFONT hfont = (HFONT)SendDlgItemMessage(hdlg,IDC_RULES,WM_GETFONT,0,0);
HDC hdc=GetDC(0); HGDIOBJ holdf=0; if (hfont!=0) holdf=SelectObject(hdc,hfont);
int maxwidth=0;
//
SendDlgItemMessage(hdlg,IDC_RULES,WM_SETREDRAW,FALSE,0);
SendDlgItemMessage(hdlg,IDC_RULES,LB_RESETCONTENT,0,0);
add->cur_rules.clear();
for (list<TRule>::const_iterator ir=add->rules.begin(); ir!=add->rules.end(); ir++)
{ string sif, sthen;
TMatchData md; md.regexp=ir->regexp; md.stick=ir->stick;
bool stdform = get_standard_re(md.regexp,md.artist,md.title,md.filename);
if (stdform)
{ if (md.title!="*") sif+="title="+md.title;
if (md.artist!="*") {if (sif!="") sif+=" and "; sif+="artist="+md.artist;}
if (md.filename!="*") {if (sif!="") sif+=" and "; sif+="filename="+md.filename;}
}
else sif=ir->regexp;
string stick = regungarble(md.stick);
if (stick=="") sthen=md.stick; else sthen=stick;
string s = "if "+sif+" then stick="+sthen;
SendDlgItemMessage(hdlg,IDC_RULES,LB_ADDSTRING,0,(LPARAM)s.c_str());
add->cur_rules.push_back(md);
RECT rc={0}; DrawText(hdc,s.c_str(),-1,&rc,DT_CALCRECT);
if (rc.right>maxwidth) maxwidth=rc.right;
}
SendDlgItemMessage(hdlg,IDC_RULES,LB_SETHORIZONTALEXTENT,maxwidth+8,0);
SendDlgItemMessage(hdlg,IDC_RULES,WM_SETREDRAW,TRUE,0);
InvalidateRect(GetDlgItem(hdlg,IDC_RULES),NULL,TRUE);
if (holdf!=0) SelectObject(hdc,holdf); ReleaseDC(0,hdc);
return TRUE;
}
case WM_APP: // populate the "recents" box. If wParam is true then we also update add->recents
{ HFONT hfont = (HFONT)SendDlgItemMessage(hdlg,IDC_RULES,WM_GETFONT,0,0);
HDC hdc=GetDC(0); HGDIOBJ holdf=0; if (hfont!=0) holdf=SelectObject(hdc,hfont);
int maxwidth=0;
//
list<string> newrecents;
SendDlgItemMessage(hdlg,IDC_RECENTS,WM_SETREDRAW,FALSE,0);
SendDlgItemMessage(hdlg,IDC_RECENTS,LB_RESETCONTENT,0,0);
add->cur_recents.clear(); add->cur_recents.reserve(add->recents.size());
REGEXP re; regbegin(&re,"ARTIST=(.*)___TITLE=(.*)___FILENAME=(.*)___STICK=(.*)___",0);
// we'll pregenerate regexps for all the rules since otherwise this would
// have a numrecents*numrules*costof(regcompile), which is too slow!
int numrules = add->rules.size(); vector<REGEXP> rerules(numrules);
int i=0; for (list<TRule>::const_iterator ir=add->rules.begin(); ir!=add->rules.end(); ir++,i++)
{ regbegin(&rerules[i],ir->regexp.c_str(),REG_ICASE);
}
//
for (list<string>::const_iterator ir=add->recents.begin(); ir!=add->recents.end(); ir++)
{ REGMATCH m[5]; const char *src=ir->c_str();
bool res = regmatch(&re,src,m,5);
if (res)
{ TMatchData md;
md.artist=string(src+m[1].i,m[1].len);
md.title=string(src+m[2].i,m[2].len);
md.filename=string(src+m[3].i,m[3].len);
md.stick=string(src+m[4].i,m[4].len); if (md.stick=="") md.stick=".*";
// replace ...Music\\stuff by just *\\stuff and .mp3/.wma by .*
string matchfn=md.filename;
size_t mpos = StringLower(matchfn).find("music\\");
if (mpos!=string::npos) matchfn="*"+matchfn.substr(mpos+5);
int len=matchfn.length();
if (len>4 && StringLower(matchfn.substr(len-4))==".mp3") matchfn=matchfn.substr(0,len-4)+".*";
if (len>4 && StringLower(matchfn.substr(len-4))==".wma") matchfn=matchfn.substr(0,len-4)+".*";
//
md.regexp="ARTIST="+reggarble(md.artist,true)+"___TITLE="+reggarble(md.title,true)+"___FILENAME="+reggarble(matchfn,true)+"___";
string mus=make_music_string(md.artist,md.title,md.filename);
bool match=false;
for (int i=0; i<numrules && !match; i++) match|=regmatch(&rerules[i],mus.c_str(),NULL,0);
if (!match)
{ newrecents.push_back(ir->c_str());
string s=md.artist;
if (s!="") s+=" -- "; s+=md.title;
if (s!="") s+=" -- "; s+=md.filename;
SendDlgItemMessage(hdlg,IDC_RECENTS,LB_ADDSTRING,0,(LPARAM)s.c_str());
add->cur_recents.push_back(md);
RECT rc={0}; DrawText(hdc,s.c_str(),-1,&rc,DT_CALCRECT);
if (rc.right>maxwidth) maxwidth=rc.right;
}
}
}
regend(&re);
for (int i=0; i<numrules; i++) regend(&rerules[i]);
if (wParam==TRUE)
{ add->recents.clear(); add->recents.splice(add->recents.begin(),newrecents);
}
SendDlgItemMessage(hdlg,IDC_RECENTS,LB_SETHORIZONTALEXTENT,maxwidth+8,0);
SendDlgItemMessage(hdlg,IDC_RECENTS,WM_SETREDRAW,TRUE,0);
InvalidateRect(GetDlgItem(hdlg,IDC_RECENTS),NULL,TRUE);
if (holdf!=0) SelectObject(hdc,holdf); ReleaseDC(0,hdc);
return TRUE;
}
case WM_COMMAND:
{ int id=LOWORD(wParam), code=HIWORD(wParam);
if (id==IDC_HELPBTN && code==BN_CLICKED)
{ string hlp = GetStickDir()+"\\associate sticks with music.stam";
string cmd = "notepad.exe \""+hlp+"\"";
STARTUPINFO si; ZeroMemory(&si,sizeof(si)); si.cb=sizeof(si);
PROCESS_INFORMATION pi; ZeroMemory(&pi,sizeof(pi));
BOOL res = CreateProcess(NULL,(char*)cmd.c_str(),NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);
if (res) {CloseHandle(pi.hProcess); CloseHandle(pi.hThread);}
else MessageBeep(0);
}
if (id==IDC_RULES && code==LBN_SELCHANGE)
{ int i = SendDlgItemMessage(hdlg,IDC_RULES,LB_GETCURSEL,0,0);
int count = SendDlgItemMessage(hdlg,IDC_RULES,LB_GETCOUNT,0,0);
EnableWindow(GetDlgItem(hdlg,IDC_MODIFY), i!=LB_ERR);
EnableWindow(GetDlgItem(hdlg,IDC_REMOVE), i!=LB_ERR);
EnableWindow(GetDlgItem(hdlg,IDC_UP), i!=LB_ERR && i!=0);
EnableWindow(GetDlgItem(hdlg,IDC_DOWN), i!=LB_ERR && i<count-1);
SendDlgItemMessage(hdlg,IDC_RECENTS,LB_SETCURSEL,(WPARAM)-1,0);
}
if (id==IDC_RECENTS && code==LBN_SELCHANGE)
{ EnableWindow(GetDlgItem(hdlg,IDC_MODIFY), false);
EnableWindow(GetDlgItem(hdlg,IDC_REMOVE), false);
EnableWindow(GetDlgItem(hdlg,IDC_UP), false);
EnableWindow(GetDlgItem(hdlg,IDC_DOWN), false);
SendDlgItemMessage(hdlg,IDC_RULES,LB_SETCURSEL,(WPARAM)-1,0);
}
if ((id==IDC_UP||id==IDC_DOWN) && code==BN_CLICKED)
{ int selrule = SendDlgItemMessage(hdlg,IDC_RULES,LB_GETCURSEL,0,0);
if (selrule!=LB_ERR)
{ list<TRule>::iterator ir=add->rules.begin();
for (int i=0; i<selrule; i++) ir++;
TRule r = *ir;
ir=add->rules.erase(ir);
if (id==IDC_UP) ir--; else ir++;
add->rules.insert(ir,r);
//
SendMessage(hdlg,WM_APP+1,0,0); // update the rules list
if (id==IDC_UP) selrule--; else selrule++;
SendDlgItemMessage(hdlg,IDC_RULES,LB_SETCURSEL,selrule,0);
SendMessage(hdlg,WM_COMMAND,(WPARAM)(IDC_RULES|(LBN_SELCHANGE<<16)),0);
}
}
if (id==IDC_REMOVE && code==BN_CLICKED)
{ int selrule = SendDlgItemMessage(hdlg,IDC_RULES,LB_GETCURSEL,0,0);
int count = SendDlgItemMessage(hdlg,IDC_RULES,LB_GETCOUNT,0,0);
if (selrule!=LB_ERR)
{ list<TRule>::iterator ir=add->rules.begin();
for (int i=0; i<selrule; i++) ir++;
add->rules.erase(ir);
SetCursor(LoadCursor(NULL,IDC_WAIT));
SendMessage(hdlg,WM_APP,0,0); // update the recents list
SendMessage(hdlg,WM_APP+1,0,0); // update the rules list
int newsel=selrule; if (newsel==count-1) newsel--;
SendDlgItemMessage(hdlg,IDC_RULES,LB_SETCURSEL,newsel,0);
SendMessage(hdlg,WM_COMMAND,(WPARAM)(IDC_RULES|(LBN_SELCHANGE<<16)),0);
SetCursor(LoadCursor(NULL,IDC_ARROW));
}
}
if ((id==IDC_MODIFY && code==BN_CLICKED) || (id==IDC_RULES && code==LBN_DBLCLK))
{ TAssocDlgData subd; subd.pre=add->pre;
int selrule = SendDlgItemMessage(hdlg,IDC_RULES,LB_GETCURSEL,0,0);
if (selrule!=LB_ERR)
{ subd.re = add->cur_rules[selrule].regexp; subd.stick=add->cur_rules[selrule].stick;
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_RULE),hdlg,RuleDlgProc,(LPARAM)&subd);
if (res==IDOK)
{ list<TRule>::iterator ir=add->rules.begin();
for (int i=0; i<selrule; i++) ir++;
ir->regexp = subd.re;
ir->stick = subd.stick;
SetCursor(LoadCursor(NULL,IDC_WAIT));
SendMessage(hdlg,WM_APP,0,0); // update the recents list
SendMessage(hdlg,WM_APP+1,0,0); // update the rules list
SendDlgItemMessage(hdlg,IDC_RULES,LB_SETCURSEL,selrule,0);
SendMessage(hdlg,WM_COMMAND,(WPARAM)(IDC_RULES|(LBN_SELCHANGE<<16)),0);
SetCursor(LoadCursor(NULL,IDC_ARROW));
}
}
}
if ((id==IDC_ADD && code==BN_CLICKED) || (id==IDC_RECENTS && code==LBN_DBLCLK))
{ TAssocDlgData subd; subd.pre=add->pre;
subd.re=make_standard_re("","","");
subd.stick = reggarble("",true);
int selrecent = SendDlgItemMessage(hdlg,IDC_RECENTS,LB_GETCURSEL,0,0);
if (selrecent!=LB_ERR) {subd.re = add->cur_recents[selrecent].regexp; subd.stick = add->cur_recents[selrecent].stick;}
int selrule = SendDlgItemMessage(hdlg,IDC_RULES,LB_GETCURSEL,0,0);
if (selrule!=LB_ERR) {subd.re = add->cur_rules[selrule].regexp; subd.stick=add->cur_rules[selrule].stick;}
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_RULE),hdlg,RuleDlgProc,(LPARAM)&subd);
if (res==IDOK)
{ TRule r; r.regexp=subd.re; r.stick=subd.stick; add->rules.push_back(r);
SetCursor(LoadCursor(NULL,IDC_WAIT));
SendMessage(hdlg,WM_APP,0,0); // update the recents list
SendMessage(hdlg,WM_APP+1,0,0); // update the rules list
SendDlgItemMessage(hdlg,IDC_RECENTS,LB_SETCURSEL,(WPARAM)-1,0);
SendDlgItemMessage(hdlg,IDC_RULES,LB_SETCURSEL,add->rules.size()-1,0);
SendMessage(hdlg,WM_COMMAND,(WPARAM)(IDC_RULES|(LBN_SELCHANGE<<16)),0);
SetCursor(LoadCursor(NULL,IDC_ARROW));
}
}
if (id==IDOK)
{ SetCursor(LoadCursor(NULL,IDC_WAIT));
SendMessage(hdlg,WM_APP,TRUE,0); // update add->recents, removing stuff that's matched
SetCursor(LoadCursor(NULL,IDC_ARROW));
}
if (id==IDOK || id==IDCANCEL) EndDialog(hdlg,id);
return TRUE;
}
}
return FALSE;
}
int APIENTRY WinMain(HINSTANCE hi, HINSTANCE, LPSTR, int)
{ hInstance=hi;
srand(GetTickCount());
for (int i=0; i<3; i++)
{ HRSRC hrsrc = FindResource(hInstance,MAKEINTRESOURCE(i+1),RT_RCDATA);
HGLOBAL hglob = LoadResource(hInstance,hrsrc);
sampledat[i] = (unsigned char*)LockResource(hglob);
samplesize[i] = SizeofResource(hInstance,hrsrc)/12;
// the sample data is stored in rows of 12 bytes: 6 for left channel, 6 for right.
}
//
char cfn[MAX_PATH]; *cfn=0; char *c=GetCommandLine();
if (*c=='"') {c++; while (*c!='"' && *c!=0) c++; if (*c=='"') c++;}
else {while (*c!=' ' && *c!=0) c++;}
while (*c==' ') c++;
bool isedit=(strncmp(c,"/edit",5)==0); if (isedit) c+=6;
char *d=cfn; if (*c=='"') {c++; while (*c!='"' && *c!=0) {*d=*c; c++; d++;} *d=0;}
else {while (*c!=' ' && *c!=0) {*d=*c; c++; d++;} *d=0;}
string fn(cfn);
string stickdir=GetStickDir();
//
bool iszipfile=false, isassocfile=false, isstickfile=false, isbadfile=false, iswrongdirfile=false;
if (!FileExists(fn)) fn="";
if (fn!="")
{ iswrongdirfile = !IsFileWithinDirectory(fn,stickdir);
HANDLE hf=CreateFile(fn.c_str(),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
if (hf==INVALID_HANDLE_VALUE) isbadfile=true; else
{ DWORD magic, red; ReadFile(hf,&magic,4,&red,NULL);
if (red!=4) isbadfile=true; else
{ if (magic==0x04034b50) iszipfile=true; // pkzip header
if (magic==0x6d696c6e) isstickfile=true; // "nlimbs=..."
if (magic==0x5a4b5453) iszipfile=true; // "STKZ - a zipped stick file"
}
CloseHandle(hf);
}
}
string fname=ChangeFileExt(StringLower(ExtractFileName(fn)),"");
if (fname=="associate sticks with music") isassocfile=true;
fname=StringLower(ExtractFileExt(fn));
if (fname==".stam") isassocfile=true;
if (isassocfile)
{ TAssocDlgData add;
load_rules(&add.rules);
load_recents(&add.recents);
vector<TPre> pre; add.pre=⪯
int res = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_ASSOCIATE),NULL,AssocDlgProc,(LPARAM)&add);
if (res==IDOK) {save_rules(&add.rules); save_recents(&add.recents,true);}
return res;
}
if (iszipfile)
{ //FixUpRedundancy(NULL);
bool wasjustastickfigure=false;
int res = InstallZipFile(fn.c_str(),&wasjustastickfigure);
if (!wasjustastickfigure) return res;
iszipfile=false; isstickfile=true;
}
iswrongdirfile &= (GetAsyncKeyState(VK_SHIFT)>=0);
iswrongdirfile &= !isedit;
char err[1000];
string category=""; bool istoonewversion=false;
if (iswrongdirfile && isstickfile)
{ TBody *b = new TBody();
bool res = LoadBody(&b,fn.c_str(),err,lbForEditing);
if (!res) isbadfile=true;
if (b->toonewversion) istoonewversion=true;
category=b->category;
delete b;
}
if (iswrongdirfile && isbadfile)
{ string nfn = ExtractFileName(fn);
string msg = "The file '"+nfn+"' does not seem to be a valid stick figure:\r\n\r\n";
msg += err;
MessageBox(NULL,msg.c_str(),"Invalid stick figure",MB_OK);
return IDCANCEL;
}
if (iswrongdirfile && istoonewversion)
{ string msg = "This stick figure requires a more up-to-date version of the plugin.\r\n"
"Download it from http://www.wischik.com/lu/senses/sticky";
MessageBox(NULL,msg.c_str(),"It's time to upgrade!",MB_OK);
return IDCANCEL;
}
if (iswrongdirfile)
{ TInstallItemInfo iii;
iii.category = category;
iii.name = CleanWebEscapeChars(ChangeFileExt(ExtractFileName(fn),""));
if (category=="") iii.desc=iii.name; else iii.desc=category+"\\"+iii.name;
iii.fn=stickdir+"\\"+iii.desc+".stk";
iii.srcfn=fn; iii.srczip=0; iii.srczi=0;
vector<TInstallItemInfo> items; items.push_back(iii);
TInstallDlgData idd(&items);
//FixUpRedundancy(NULL);
return DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_INSTALL),NULL,InstallDlgProc,(LPARAM)&idd);
}
RegLoadUser();
INITCOMMONCONTROLSEX icx; ZeroMemory(&icx,sizeof(icx)); icx.dwSize=sizeof(icx); icx.dwICC=ICC_BAR_CLASSES;
InitCommonControlsEx(&icx);
StickClipboardFormat = RegisterClipboardFormat("StickFigure");
TEditor *editor = new TEditor();
WNDCLASSEX wcex; ZeroMemory(&wcex,sizeof(wcex)); wcex.cbSize = sizeof(WNDCLASSEX);
BOOL res=GetClassInfoEx(hInstance,"Stick3ConfClass",&wcex);
if (!res)
{ wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)EditWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL,MAKEINTRESOURCE(1));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDR_MENU);
wcex.lpszClassName = "Stick3ConfClass";
wcex.hIconSm = NULL;
ATOM res=RegisterClassEx(&wcex);
if (res==0) {MessageBox(NULL,"Failed to register class","Error",MB_OK); return 0;}
}
//
ZeroMemory(&wcex,sizeof(wcex)); wcex.cbSize = sizeof(WNDCLASSEX);
res=GetClassInfoEx(hInstance,"Stick3ClientClass",&wcex);
if (!res)
{ wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)ClientWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = 0;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = "Stick3ClientClass";
wcex.hIconSm = NULL;
ATOM res=RegisterClassEx(&wcex);
if (res==0) {MessageBox(NULL,"Failed to register class","Error",MB_OK); return 0;}
}
//
editor->mhwnd = CreateWindowEx(0,"Stick3ConfClass", "Sticky Editing",
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 460, NULL, NULL, hInstance, editor);
if (editor->mhwnd==NULL) {MessageBox(NULL,"Failed to create window","Error",MB_OK); return 0;}
hwnd_acc = editor->mhwnd;
HICON h=(HICON)LoadImage(hInstance,MAKEINTRESOURCE(2),IMAGE_ICON,16,16,0);
SendMessage(editor->mhwnd,WM_SETICON,ICON_SMALL,(LPARAM)h);
editor->hstatwnd=CreateWindowEx(0,STATUSCLASSNAME,0,SBARS_SIZEGRIP|WS_VISIBLE|WS_CHILD,0,0,0,0,editor->mhwnd,(HMENU)1,hInstance,0);
SendMessage(editor->hstatwnd,SB_SIMPLE,TRUE,0);
editor->chwnd=CreateWindowEx(0,"Stick3ClientClass",0,WS_HSCROLL|WS_VSCROLL|WS_CHILD|WS_VISIBLE,0,0,0,0,editor->mhwnd,(HMENU)2,hInstance,editor);
hac = LoadAccelerators(hInstance,MAKEINTRESOURCE(IDR_ACCELERATORS));
ShowWindow(editor->mhwnd,SW_SHOW);
//FixUpRedundancy(editor->mhwnd);
if (!FileExists(fn)) fn="";
if (fn=="") {strcpy(editor->curfile,""); editor->ShowHint(""); ShowAngles=true; ShowJoints=true; ShowInvisibles=true;}
else
{ char err[1000];
bool res=LoadBody(&editor->body,fn.c_str(),err,lbForEditing);
if (res)
{ strcpy(editor->curfile,fn.c_str()); editor->tool=tEdit;
string msg = "Opened file "+ChangeFileExt(ExtractFileName(fn),""); editor->ShowHint(msg);
}
else
{ strcpy(editor->curfile,"");
strcat(err,"\r\nUnable to open file "); strcat(err,fn.c_str());
MessageBox(editor->mhwnd,err,"Sticky",MB_OK);
editor->ShowHint("");
}
}
editor->FileReady();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{ if (!TranslateAccelerator(editor->mhwnd,hac,&msg))
{ TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
RegSaveUser();
delete editor;
return msg.wParam;
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// SetDlgItemUrl(hwnd,IDC_MYSTATIC,"http://www.wischik.com/lu");
// This routine turns a dialog's static text control into an underlined hyperlink.
// You can call it in your WM_INITDIALOG, or anywhere.
// It will also set the text of the control... if you want to change the text
// back, you can just call SetDlgItemText() afterwards.
// --------------------------------------------------------------------------------
void SetDlgItemUrl(HWND hdlg,int id,const char *url);
// Implementation notes:
// We have to subclass both the static control (to set its cursor, to respond to click)
// and the dialog procedure (to set the font of the static control). Here are the two
// subclasses:
LRESULT CALLBACK UrlCtlProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
LRESULT CALLBACK UrlDlgProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
// When the user calls SetDlgItemUrl, then the static-control-subclass is added
// if it wasn't already there, and the dialog-subclass is added if it wasn't
// already there. Both subclasses are removed in response to their respective
// WM_DESTROY messages. Also, each subclass stores a property in its window,
// which is a HGLOBAL handle to a GlobalAlloc'd structure:
typedef struct {char *url; WNDPROC oldproc; HFONT hf; HBRUSH hb;} TUrlData;
// I'm a miser and only defined a single structure, which is used by both
// the control-subclass and the dialog-subclass. Both of them use 'oldproc' of course.
// The control-subclass only uses 'url' (in response to WM_LBUTTONDOWN),
// and the dialog-subclass only uses 'hf' and 'hb' (in response to WM_CTLCOLORSTATIC)
// There is one sneaky thing to note. We create our underlined font *lazily*.
// Initially, hf is just NULL. But the first time the subclassed dialog received
// WM_CTLCOLORSTATIC, we sneak a peak at the font that was going to be used for
// the control, and we create our own copy of it but including the underline style.
// This way our code works fine on dialogs of any font.
// SetDlgItemUrl: this is the routine that sets up the subclassing.
void SetDlgItemUrl(HWND hdlg,int id,const char *url)
{ // nb. vc7 has crummy warnings about 32/64bit. My code's perfect! That's why I hide the warnings.
#pragma warning( push )
#pragma warning( disable: 4312 4244 )
// First we'll subclass the edit control
HWND hctl = GetDlgItem(hdlg,id);
SetWindowText(hctl,url);
HGLOBAL hold = (HGLOBAL)GetProp(hctl,"href_dat");
if (hold!=NULL) // if it had been subclassed before, we merely need to tell it the new url
{ TUrlData *ud = (TUrlData*)GlobalLock(hold);
delete[] ud->url;
ud->url=new char[strlen(url)+1]; strcpy(ud->url,url);
}
else
{ HGLOBAL hglob = GlobalAlloc(GMEM_MOVEABLE,sizeof(TUrlData));
TUrlData *ud = (TUrlData*)GlobalLock(hglob);
ud->oldproc = (WNDPROC)GetWindowLongPtr(hctl,GWLP_WNDPROC);
ud->url=new char[strlen(url)+1]; strcpy(ud->url,url);
ud->hf=0; ud->hb=0;
GlobalUnlock(hglob);
SetProp(hctl,"href_dat",hglob);
SetWindowLongPtr(hctl,GWLP_WNDPROC,(LONG_PTR)UrlCtlProc);
}
//
// Second we subclass the dialog
hold = (HGLOBAL)GetProp(hdlg,"href_dlg");
if (hold==NULL)
{ HGLOBAL hglob = GlobalAlloc(GMEM_MOVEABLE,sizeof(TUrlData));
TUrlData *ud = (TUrlData*)GlobalLock(hglob);
ud->url=0;
ud->oldproc = (WNDPROC)GetWindowLongPtr(hdlg,GWLP_WNDPROC);
ud->hb=CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
ud->hf=0; // the font will be created lazilly, the first time WM_CTLCOLORSTATIC gets called
GlobalUnlock(hglob);
SetProp(hdlg,"href_dlg",hglob);
SetWindowLongPtr(hdlg,GWLP_WNDPROC,(LONG_PTR)UrlDlgProc);
}
#pragma warning( pop )
}
// UrlCtlProc: this is the subclass procedure for the static control
LRESULT CALLBACK UrlCtlProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ HGLOBAL hglob = (HGLOBAL)GetProp(hwnd,"href_dat");
if (hglob==NULL) return DefWindowProc(hwnd,msg,wParam,lParam);
TUrlData *oud=(TUrlData*)GlobalLock(hglob); TUrlData ud=*oud;
GlobalUnlock(hglob); // I made a copy of the structure just so I could GlobalUnlock it now, to be more local in my code
switch (msg)
{ case WM_DESTROY:
{ RemoveProp(hwnd,"href_dat"); GlobalFree(hglob);
if (ud.url!=0) delete[] ud.url;
// nb. remember that ud.url is just a pointer to a memory block. It might look weird
// for us to delete ud.url instead of oud->url, but they're both equivalent.
} break;
case WM_LBUTTONDOWN:
{ HWND hdlg=GetParent(hwnd); if (hdlg==0) hdlg=hwnd;
ShellExecute(hdlg,"open",ud.url,NULL,NULL,SW_SHOWNORMAL);
} break;
case WM_SETCURSOR:
{ SetCursor(LoadCursor(NULL,MAKEINTRESOURCE(IDC_HAND)));
return TRUE;
}
case WM_NCHITTEST:
{ return HTCLIENT; // because normally a static returns HTTRANSPARENT, so disabling WM_SETCURSOR
}
}
return CallWindowProc(ud.oldproc,hwnd,msg,wParam,lParam);
}
// UrlDlgProc: this is the subclass procedure for the dialog
LRESULT CALLBACK UrlDlgProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ HGLOBAL hglob = (HGLOBAL)GetProp(hwnd,"href_dlg");
if (hglob==NULL) return DefWindowProc(hwnd,msg,wParam,lParam);
TUrlData *oud=(TUrlData*)GlobalLock(hglob); TUrlData ud=*oud;
GlobalUnlock(hglob);
switch (msg)
{ case WM_DESTROY:
{ RemoveProp(hwnd,"href_dlg"); GlobalFree(hglob);
if (ud.hb!=0) DeleteObject(ud.hb);
if (ud.hf!=0) DeleteObject(ud.hf);
} break;
case WM_CTLCOLORSTATIC:
{ HDC hdc=(HDC)wParam; HWND hctl=(HWND)lParam;
// To check whether to handle this control, we look for its subclassed property!
HANDLE hprop=GetProp(hctl,"href_dat"); if (hprop==NULL) return CallWindowProc(ud.oldproc,hwnd,msg,wParam,lParam);
// There has been a lot of faulty discussion in the newsgroups about how to change
// the text colour of a static control. Lots of people mess around with the
// TRANSPARENT text mode. That is incorrect. The correct solution is here:
// (1) Leave the text opaque. This will allow us to re-SetDlgItemText without it looking wrong.
// (2) SetBkColor. This background colour will be used underneath each character cell.
// (3) return HBRUSH. This background colour will be used where there's no text.
SetTextColor(hdc,RGB(0,0,255));
SetBkColor(hdc,GetSysColor(COLOR_BTNFACE));
if (ud.hf==0)
{ // we use lazy creation of the font. That's so we can see font was currently being used.
TEXTMETRIC tm; GetTextMetrics(hdc,&tm);
LOGFONT lf;
lf.lfHeight=tm.tmHeight;
lf.lfWidth=0;
lf.lfEscapement=0;
lf.lfOrientation=0;
lf.lfWeight=tm.tmWeight;
lf.lfItalic=tm.tmItalic;
lf.lfUnderline=TRUE;
lf.lfStrikeOut=tm.tmStruckOut;
lf.lfCharSet=tm.tmCharSet;
lf.lfOutPrecision=OUT_DEFAULT_PRECIS;
lf.lfClipPrecision=CLIP_DEFAULT_PRECIS;
lf.lfQuality=DEFAULT_QUALITY;
lf.lfPitchAndFamily=tm.tmPitchAndFamily;
GetTextFace(hdc,LF_FACESIZE,lf.lfFaceName);
ud.hf=CreateFontIndirect(&lf);
TUrlData *oud = (TUrlData*)GlobalLock(hglob); oud->hf=ud.hf; GlobalUnlock(hglob);
}
SelectObject(hdc,ud.hf);
// Note: the win32 docs say to return an HBRUSH, typecast as a BOOL. But they
// fail to explain how this will work in 64bit windows where an HBRUSH is 64bit.
// I have supressed the warnings for now, because I hate them...
#pragma warning( push )
#pragma warning( disable: 4311 )
return (BOOL)ud.hb;
#pragma warning( pop )
}
}
return CallWindowProc(ud.oldproc,hwnd,msg,wParam,lParam);
}
|
6f5a7a5017c8831ff0662e7f5fe309f3ca7efd21 | bc7f6f3ce84e3592033132186c8651d7a37e460e | /intrin/Vu64IdxLowBit.hpp | 9c36c8cdb6fcb35de8cd553c8b08762e4c173e94 | [] | no_license | EAirPeter/vmp | f3dc79fb789b7523e488fdca14e75b0dc0be968c | e5b0fdf550b4a6cacccc8e9e8a08fc3102743b90 | refs/heads/master | 2021-01-21T07:10:30.239044 | 2017-05-18T17:37:39 | 2017-05-18T17:37:39 | 91,602,649 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,706 | hpp | Vu64IdxLowBit.hpp | #ifndef VMP_INTRIN_VU64_IDXLOWBIT_HPP_
#define VMP_INTRIN_VU64_IDXLOWBIT_HPP_
#include "../Common.hpp"
#define VMP_VU64_ILB_ASM_QWD(ops_) \
U64 uRes; \
asm volatile ( \
ops_ \
"L_End_%=:" \
: [res]"+&r"(uRes = 0) \
: [len]"i"(0), \
[dat]"r"(pData) \
: "cc" \
); \
return uRes
#define VMP_VU64_ILB_ASM_VEC(ops_) \
__m256i yTmp; \
U64 uIter, uRes; \
asm volatile ("\n" \
"L_Loop_%=:\n\t" \
"vmovdqu %[tmp], ymmword ptr[%[dat] + %[itr]]\n\t" \
"vptest %[tmp], %[tmp]\n\t" \
"jnz L_InYmm_%=\n\t" \
"add %[itr], 32\n\t" \
"jnz L_Loop_%=\n\t" \
ops_ \
"jmp L_End_%=\n" \
"L_InYmm_%=:\n\t" \
"test qword ptr[%[dat] + %[itr]], -1\n\t" \
"jnz L_Done_%=\n\t" \
"mov %[res], %[len] + 1\n\t" \
"test qword ptr[%[dat] + %[itr] + 8], -1\n\t" \
"jnz L_Done_%=\n\t" \
"mov %[res], %[len] + 2\n\t" \
"test qword ptr[%[dat] + %[itr] + 16], -1\n\t" \
"jnz L_Done_%=\n\t" \
"mov %[res], %[len] + 3\n\t" \
"L_Done_%=:\n\t" \
"sar %[itr], 3\n\t" \
"add %[res], %[itr]\n\t" \
"L_End_%=:" \
: [tmp]"=&x"(yTmp), \
[itr]"+&r"(uIter = -(kLength >> 2 << 5)), \
[res]"+&r"(uRes = kLength >> 2 << 2) \
: [len]"i"(kLength >> 2 << 2), \
[dat]"r"(pData + (kLength >> 2 << 2)) \
: "cc" \
); \
return uRes;
#define VMP_VU64_ILB_ASM_OPR(off_) \
"test qword ptr[%[dat] + " off_ " * 8], -1\n\t" \
"jnz L_End_%=\n\t" \
"mov %[res], %[len] + " off_ " + 1\n\t" \
namespace vmp::intrin {
template<U64 kLength> inline
U64 Vu64IdxLowBit(const U64 *pData) noexcept {
constexpr U64 uLenMod = kLength & 3;
if constexpr (uLenMod == 3) {
VMP_VU64_ILB_ASM_VEC(
VMP_VU64_ILB_ASM_OPR("0")
VMP_VU64_ILB_ASM_OPR("1")
VMP_VU64_ILB_ASM_OPR("2")
);
}
else if constexpr (uLenMod == 2) {
VMP_VU64_ILB_ASM_VEC(
VMP_VU64_ILB_ASM_OPR("0")
VMP_VU64_ILB_ASM_OPR("1")
);
}
else if constexpr (uLenMod == 1) {
VMP_VU64_ILB_ASM_VEC(
VMP_VU64_ILB_ASM_OPR("0")
);
}
else {
VMP_VU64_ILB_ASM_VEC(
""
);
}
}
template<> inline
U64 Vu64IdxLowBit<4>(const U64 *pData) noexcept {
VMP_VU64_ILB_ASM_QWD(
VMP_VU64_ILB_ASM_OPR("0")
VMP_VU64_ILB_ASM_OPR("1")
VMP_VU64_ILB_ASM_OPR("2")
VMP_VU64_ILB_ASM_OPR("3")
);
}
template<> inline
U64 Vu64IdxLowBit<3>(const U64 *pData) noexcept {
VMP_VU64_ILB_ASM_QWD(
VMP_VU64_ILB_ASM_OPR("0")
VMP_VU64_ILB_ASM_OPR("1")
VMP_VU64_ILB_ASM_OPR("2")
);
}
template<> inline
U64 Vu64IdxLowBit<2>(const U64 *pData) noexcept {
VMP_VU64_ILB_ASM_QWD(
VMP_VU64_ILB_ASM_OPR("0")
VMP_VU64_ILB_ASM_OPR("1")
);
}
template<> inline
U64 Vu64IdxLowBit<1>(const U64 *pData) noexcept {
VMP_VU64_ILB_ASM_QWD(
VMP_VU64_ILB_ASM_OPR("0")
);
}
template<> inline
U64 Vu64IdxLowBit<0>(const U64 *) noexcept {
return 0;
}
}
#endif // ifndef VMP_INTRIN_VU64_IDXIDXLOWBIT_HPP_
|
c7ef2cd5f45a84a45fc015b5b20ccee864858a28 | f0c29a2ad1a31540dd1640a6b4b86938c090443f | /src/GameObject/2D/Physic.cpp | 1252973a08d12d8a0be684218d9aa9b6ced32dfe | [
"MIT"
] | permissive | Hazurl/Framework-haz | 2e381b089610dea04f4171f5c9dde20d89741af6 | 370348801cd969ce8521264653069923a255e0b0 | refs/heads/master | 2021-01-01T19:41:08.151172 | 2017-09-17T14:16:53 | 2017-09-17T14:16:53 | 98,648,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,452 | cpp | Physic.cpp | #include <haz/GameObject/2D/Physic.hpp>
BEG_NAMESPACE_HAZ_COLLISION
bool point_in_box(BoxCollider const& b, Vectorf point) {
point -= b.transform()->globalPosition();
return haz::between_ii(point.x, b.left(), b.right())
&& haz::between_ii(point.y, b.top(), b.bottom());
}
bool point_in_circle(CircleCollider const& c, Vectorf point) {
point -= c.transform()->globalPosition();
return (c.position() - point).magnitude2() <= c.radius * c.radius;
}
bool point_in_polygon(PolygonCollider const& p, Vectorf point) {
point -= p.transform()->globalPosition();
const auto points = p.getPath();
bool res = false;
for (unsigned int pos = 0, prev = points.size() - 1; pos < points.size(); prev = pos++) {
auto cur = points[pos];
auto last = points[prev];
if (((cur.y <= point.y) && (last.y >= point.y)) || ((last.y <= point.y) && (cur.y >= point.y))) {
auto deno = last.y - cur.y;
if (deno == 0) {
return (((cur.x <= point.x) && (last.x >= point.x)) || ((last.x <= point.x) && (cur.x >= point.x)));
} else {
auto cross = (last.x - cur.x) * (point.y - cur.y) / deno + cur.x;
if (cross == point.x)
return true;
if (cross <= point.x) {
if (cross == cur.x && point.y == cur.y) {
if (cur.y > last.y)
res = !res;
} else if(cross == last.x && point.y == last.y) {
if (cur.y < last.y)
res = !res;
} else {
res = !res;
}
}
}
}
}
return res;
}
bool point_in_edge(EdgeCollider const& e, Vectorf point) {
point -= e.transform()->globalPosition();
if (e.points.size() <= 1) {
return e.points.size() == 0 ? false :
point_in_circle({nullptr, e.points[0], e.radius}, point);
}
float d_min = -1;
for (unsigned int pos = 1; pos < e.points.size(); ++pos) {
if (d_min == -1)
d_min = (getClosestPointInEdge(e.points[pos - 1], e.points[pos], point) - point).magnitude2();
else
d_min = min(d_min, (getClosestPointInEdge(e.points[pos - 1], e.points[pos], point) - point).magnitude2());
}
return d_min <= e.radius * e.radius;
}
Vectorf getClosestPointInEdge(Vectorf const& a, Vectorf const& b, Vectorf const& point) {
auto seg = b - a;
auto normal = seg.orthogonal();
return Vectorf::lerpClamp(
(a.x * normal.y - point.x * normal.y - normal.x * a.y + normal.x * point.y) / (seg.y * normal.x - seg.x * normal.y)
, a, b);
}
bool has_edge_intersection(Vectorf const& a, Vectorf const& b, Vectorf const& c, Vectorf const& d) {
auto e0 = b - a;
auto e1 = d - c;
float deno = e0.y * e1.x - e0.x * e1.y;
float k = (a.x * e1.y - c.x * e1.y - e1.x * a.y + e1.x * c.y) / deno;
float m = (e0.x * a.y - e0.x * c.y - a.x * e0.y + c.x * e0.y) / deno;
return between_ii<float>(k, 0, 1) && between_ii<float>(m, 0, 1);
}
bool edge_intersection(Vectorf& result, Vectorf const& a, Vectorf const& b, Vectorf const& c, Vectorf const& d) {
auto e0 = b - a;
auto e1 = d - c;
float deno = e0.y * e1.x - e0.x * e1.y;
if (deno == 0) {
return false;
}
float m = (e0.x * a.y - e0.x * c.y - a.x * e0.y + c.x * e0.y) / deno;
float k = (a.x * e1.y - c.x * e1.y - e1.x * a.y + e1.x * c.y) / deno;
if (between_ii<float>(k, 0, 1) && between_ii<float>(m, 0, 1)) {
result = a + e0 * m;
return true;
} else {
return false;
}
}
END_NAMESPACE_HAZ_COLLISION
BEG_NAMESPACE_HAZ_HIDDEN
void _test_Collision_Polygon () {
USING_NS_HAZ_2D
USING_NS_HAZ_COLLISION
#define TEST_SQUARE(n, v...) WRITE(n " >>> " << (Vectorf v) << " : " << Collision::point_in_polygon(p, (Vectorf v)) << std::endl);
PolygonCollider p(nullptr, {
{25, 25}, {75, 25}, {75, 75}, {25, 75}
});
WRITE(" Y ^ ");
WRITE(" | ");
WRITE(" 100 | Y ");
WRITE(" | ");
WRITE(" 75 | D----CD---C ");
WRITE(" | | | ");
WRITE(" 50 |Z DA O BC X ");
WRITE(" | | | ");
WRITE(" 25 | A----AB---B ");
WRITE(" | ");
WRITE(" 0 | W ");
WRITE(" -------------------------> X");
WRITE(" 0 25 50 75 100 " << std::endl);
TEST_SQUARE("A (true)", {25, 25})
TEST_SQUARE("B (true)", {75, 25})
TEST_SQUARE("C (true)", {75, 75})
TEST_SQUARE("D (true)", {75, 25})
TEST_SQUARE("AB (true)", {50, 25})
TEST_SQUARE("BC (true)", {75, 50})
TEST_SQUARE("CD (true)", {50, 75})
TEST_SQUARE("DA (true)", {25, 50})
TEST_SQUARE("O (true)", {50, 50})
TEST_SQUARE("W (false)", {50, 0})
TEST_SQUARE("X (false)", {100, 50})
TEST_SQUARE("Y (false)", {50, 100})
TEST_SQUARE("Z (false)", {0, 50})
p.setPath({
{50, 0}, {100, 50}, {50, 100}, {0, 50}
});
std::cout << std::endl;
WRITE(" Y ^ ");
WRITE(" | ");
WRITE(" 100 |Z D Y ");
WRITE(" | / \\ ");
WRITE(" 75 | DA CD ");
WRITE(" | / \\ ");
WRITE(" 50 |A O C ");
WRITE(" | \\ / ");
WRITE(" 25 | AB BC ");
WRITE(" | \\ / ");
WRITE(" 0 |W B X ");
WRITE(" ---------------------> X");
WRITE(" 0 25 50 75 100 " << std::endl);
TEST_SQUARE("A (true)", {0, 50})
TEST_SQUARE("B (true)", {50, 0})
TEST_SQUARE("C (true)", {100, 50})
TEST_SQUARE("D (true)", {50, 100})
TEST_SQUARE("AB (true)", {25, 25})
TEST_SQUARE("BC (true)", {75, 25})
TEST_SQUARE("CD (true)", {75, 75})
TEST_SQUARE("DA (true)", {25, 75})
TEST_SQUARE("O (true)", {50, 50})
TEST_SQUARE("W (false)", {0, 0})
TEST_SQUARE("X (false)", {100, 0})
TEST_SQUARE("Y (false)", {100, 100})
TEST_SQUARE("Z (false)", {0, 100})
}
END_NAMESPACE_HAZ_HIDDEN |
6c4a32cb94f9ca4b7cd5c69f7decea0d7dd775b7 | 28e4073b48688904621621d82820138496400f5a | /SRC/Editorfr.cpp | 22ef1d8f96105de5e459151961157577a35ab32c | [
"Apache-2.0"
] | permissive | gtoffoli/iperlogo | 3a8bb3d0a6c1b90b60e91d2aeeb2133ed0b3d452 | 568fd89addbd90c35cdc7b2620705faa6f488f8e | refs/heads/main | 2023-08-30T16:28:00.234811 | 2021-11-15T23:48:57 | 2021-11-15T23:48:57 | 428,443,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,281 | cpp | Editorfr.cpp | // editorfr.cpp : implementation file
//
/* EDITORFR.CPP
010605 menu sotto condizione iperlogoIsMenu
980624 introdotto opzione ForceTopmost
*/
#include "stdafx.h"
#include "iperlogo.h"
#include "ilcpp.h"
#include "editorfr.h"
#include "editorvw.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
extern char DefaultEditor[];
extern CREATESTRUCT Editor;
extern char EditorFont[];
extern node FontToList (LOGFONT* lpLogFont);
extern BOOL ForceTopmost;
extern int iperlogoIsMenu; // 010605
/////////////////////////////////////////////////////////////////////////////
// CEditorFrame
IMPLEMENT_DYNCREATE(CEditorFrame, CFrameWnd)
CEditorFrame::CEditorFrame()
{
}
CEditorFrame::~CEditorFrame()
{
}
//> 981123
#define yesTitleStyles (WS_SYSMENU | WS_OVERLAPPED | WS_CAPTION | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX)
#define noTitleStyles (WS_POPUP /* | WS_BORDER */)
#define andTitleStyles (yesTitleStyles & noTitleStyles)
//<
BOOL CEditorFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if (! CFrameWnd::PreCreateWindow(cs)) return FALSE;
cs.x=Editor.x;
cs.y=Editor.y;
cs.cx=Editor.cx;
cs.cy=Editor.cy;
cs.hMenu=0;
//>010605
// if (Editor.hMenu)
if (iperlogoIsMenu && Editor.hMenu)
//<010605
cs.hMenu=LoadMenu(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_EDITOR));
cs.style=cs.style &
(~ (WS_SYSMENU | WS_THICKFRAME | WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
if (Editor.lpszName == (char *) 0L) {
m_title[0] = '\0';
// cs.style |= (WS_POPUP | WS_BORDER);
cs.style |= noTitleStyles;
} else {
strcpy (m_title, Editor.lpszName);
// cs.style |= (WS_SYSMENU | WS_OVERLAPPED | WS_CAPTION | WS_BORDER | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX);
cs.style |= yesTitleStyles;
}
//>980624
if (ForceTopmost)
cs.dwExStyle |= WS_EX_TOPMOST;
//<980624
return TRUE;
}
static UINT NEAR WM_FINDREPLACE = ::RegisterWindowMessage(FINDMSGSTRING); // added
BEGIN_MESSAGE_MAP(CEditorFrame, CFrameWnd)
//{{AFX_MSG_MAP(CEditorFrame)
ON_WM_CLOSE()
ON_WM_DESTROY()
//}}AFX_MSG_MAP
ON_REGISTERED_MESSAGE( WM_FINDREPLACE, OnFindReplace ) // added
END_MESSAGE_MAP()
void CEditorFrame::SetTitleBar (BOOL setOn)
{
BOOL isOn;
DWORD dwAdd, dwRemove, nFlags = 1;
DWORD oldStyles = GetStyle ();
isOn = oldStyles & WS_DLGFRAME;
if ((setOn && isOn) || ((! setOn) && (! isOn)))
return;
if (setOn) {
dwRemove = noTitleStyles & (~andTitleStyles);
dwAdd = yesTitleStyles & (~andTitleStyles);
} else {
dwRemove = yesTitleStyles & (~andTitleStyles);
dwAdd = noTitleStyles & (~andTitleStyles);
}
BOOL isModified =
ModifyStyle (dwRemove, dwAdd, nFlags);
DWORD newStyles = GetStyle ();
// tentativo di ridisegnare il frame
// per rendere effettivo il cambiamento di stile
if (GetMenu () != NULL)
DrawMenuBar();
else if (m_hMenu != NULL) {
SetMenuBar (TRUE);
SetMenuBar (FALSE);
}
}
void CEditorFrame::SetMenuBar (BOOL setOn)
{
BOOL isOn = (GetMenu () != NULL);
if ((setOn && isOn) || ((! setOn) && (! isOn)))
return;
if (setOn)
::SetMenu (m_hWnd, m_hMenu);
else {
m_hMenu = ::GetMenu (m_hWnd);
::SetMenu (m_hWnd, NULL);
}
}
/////////////////////////////////////////////////////////////////////////////
// CEditorFrame message handlers
// The framework calls this member function as a signal that
// the CWnd or an application is to terminate.
// The default implementation calls DestroyWindow.
void CEditorFrame::OnClose()
{
// TODO: Add your message handler code here and/or call default
// close client view
CEditorView* editorView = (CEditorView*) GetActiveView();
editorView->OnFileClose();
}
void CEditorFrame::OnDestroy()
{
CFrameWnd::OnDestroy();
// TODO: Add your message handler code here
// record current normal position of the window
char name [MAX_CHARS];
CEditorView* editorView = (CEditorView*) GetActiveView();
editorView->GetName(name);
if (strcmp (name, DefaultEditor) == 0) {
WINDOWPLACEMENT wndPl;
if (GetWindowPlacement (&wndPl)) {
RECT pos = wndPl.rcNormalPosition;
Editor.x = pos.left;
Editor.y = pos.top;
Editor.cx = pos.right - pos.left;
Editor.cy = pos.bottom - pos.top;
}
MemScrivi (EditorFont, FontToList(&(editorView->m_logFont)));
}
}
|
c3f6ce0d87a5db58f3efd88de39d7f6e1f96efab | 8aed073f8b738ed96de49517f6f517676c0b0f88 | /day05/ex02/RobotomyRequest.cpp | d5f9e6bd91c952103cf4581c0309239ac145322c | [] | no_license | morrkof/CPP_piscine | 4dee3b627c96927e2f4bbe20b6c49f9aa26fcc16 | fd11644b085df079fedd49d21ecae8c2ca8f83f6 | refs/heads/master | 2023-06-17T20:47:44.636468 | 2021-07-17T23:55:22 | 2021-07-17T23:55:22 | 373,429,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,797 | cpp | RobotomyRequest.cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* RobotomyRequest.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ppipes <ppipes@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/16 13:05:40 by ppipes #+# #+# */
/* Updated: 2021/03/18 23:01:32 by ppipes ### ########.fr */
/* */
/* ************************************************************************** */
#include "RobotomyRequest.hpp"
#include <cstdlib>
RobotomyRequest::RobotomyRequest(std::string target):
Form("Robotomy Request", 72, 45), _target(target){}
void RobotomyRequest::execute(Bureaucrat const &executor) const{
executor.executeForm(*this);
if (this->getSigned() == 0)
throw Form::NoSignedException();
if (executor.getGrade() > 45)
throw Form::GradeTooLowException();
const std::string message[2] = {" has been robotomized succesfully.", " failed to robotomize."};
srand((time(0)));
std::cout << this->_target << message[rand() % 2] << std::endl;
}
/* COPLIEN FORM */
RobotomyRequest::RobotomyRequest(void):
Form("Robotomy Request", 72, 45), _target("undefined"){}
RobotomyRequest::~RobotomyRequest(){}
RobotomyRequest::RobotomyRequest(RobotomyRequest const &src): Form(src){}
RobotomyRequest &RobotomyRequest::operator=(RobotomyRequest const &src){
(void)src;
return *this;
} |
fa48d618633cae04ad10ea0df739a9e0a1cedd7f | 57094f87358bb887a80aefdaea6009295a14704c | /Src/Engine/Rendering/RendererManager.cpp | 8be022cfc0d36051ac06af65ec5ced5623d0bc52 | [] | no_license | Huangxy0106/CXCEngine | 49c884cc91334adb376c6998ec6c16e4527ab2f8 | e14cdca6afdff0a145149f355ea92d46cf982dc6 | refs/heads/master | 2021-10-12T04:06:08.924364 | 2019-02-01T16:00:49 | 2019-02-01T16:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,559 | cpp | RendererManager.cpp | #include "Rendering/RendererManager.h"
#include "Rendering/ForwardRenderer.h"
#include "Rendering/DebugMeshRenderPipeline.h"
#include "Rendering/RendererContext.h"
#include "Geometry/Mesh.h"
#include "Geometry/DebugMesh.h"
#include "Utilities/DebugLogger.h"
#include "Geometry/SubMesh.h"
const std::string DebugMeshVSSourceCode = "#version 430 core \n" \
"layout(location = 0) in vec3 vertexPosition_modelspace;\n " \
"uniform mat4 P;\n" \
"uniform mat4 V;\n" \
"uniform mat4 M;\n" \
"mat4 MVP = P * V * M;\n"\
"void main()\n" \
"{\n" \
"gl_Position = MVP * vec4(vertexPosition_modelspace, 1);\n" \
"}\n";
const std::string DebugMeshFSSourceCode = "#version 430 core\n" \
"out vec3 OutColor;\n"\
"uniform vec3 VertexColor;\n" \
"void main()\n" \
"{\n" \
"OutColor = VertexColor;\n"\
"}\n";
namespace cxc
{
RendererManager::RendererManager()
{
}
RendererManager::~RendererManager()
{
}
void RendererManager::BindDebugMesh(std::shared_ptr<DebugMesh> pMesh)
{
if (pMesh)
{
auto DebugRendererIter = RenderersMap.find("DebugMeshRenderer");
if (DebugRendererIter != RenderersMap.end())
{
BindMeshRenderer(pMesh, DebugRendererIter->second);
}
}
}
void RendererManager::CreateEngineDefaultRenderer()
{
// Create engine defalut renderer
// Create debug mesh renderer and pipeline
auto DebugMeshVS = NewObject<Shader>();
auto DebugMeshFS = NewObject<Shader>();
DebugMeshVS->ShaderName = "DebugMeshVS"; DebugMeshVS->ShaderType = eShaderType::VERTEX_SHADER;
DebugMeshFS->ShaderName = "DebugMeshFS"; DebugMeshFS->ShaderType = eShaderType::FRAGMENT_SHADER;
std::string CompileLog;
bool bResult = DebugMeshVS->CompileShader(DebugMeshVSSourceCode, CompileLog);
if (!bResult)
DEBUG_LOG(eLogType::Error, "RendererManager::CreateEngineDefaultRenderer, Failed to compile debug mesh vertex shader, OutLog : " + CompileLog + '\n');
bResult = DebugMeshFS->CompileShader(DebugMeshFSSourceCode, CompileLog);
if (!bResult)
DEBUG_LOG(eLogType::Error, "RendererManager::CreateEngineDefaultRenderer, Failed to compile debug mesh fragment shader, OutLog : " + CompileLog + '\n');
auto DebugMeshPipeline = NewObject<DebugMeshRenderPipeline>();
DebugMeshPipeline->AttachShader(DebugMeshVS);
DebugMeshPipeline->AttachShader(DebugMeshFS);
auto DebugMeshRenderer = NewObject<ForwardRenderer>("DebugMeshRenderer");
DebugMeshRenderer->PushPipeline(DebugMeshPipeline);
DebugMeshRenderer->InitializeRenderer();
AddRenderer(DebugMeshRenderer);
}
void RendererManager::SetCurrentUsedRenderer(std::shared_ptr<SubMeshRenderer> pRenderer)
{
CurrentUsedRenderer = pRenderer;
}
std::shared_ptr<Shader> RendererManager::FactoryShader(const std::string& ShaderName, eShaderType ShaderType, const std::string& ShaderFileName)
{
auto pNewShader = NewObject<Shader>(ShaderName, ShaderFileName, ShaderType);
if (pNewShader && pNewShader->CompileShader())
{
pNewShader->ShaderFileName = ShaderFileName;
AddShader(pNewShader);
return pNewShader;
}
else
return nullptr;
}
std::shared_ptr<Shader>RendererManager::GetShader(const std::string& ShaderName)
{
auto iter = pShadersMap.find(ShaderName);
if (iter != pShadersMap.end())
{
return iter->second;
}
else
return nullptr;
}
void RendererManager::AddShader(std::shared_ptr<Shader> pShader)
{
if (pShader)
{
pShadersMap.insert(std::make_pair(pShader->GetShaderName(), pShader));
}
}
std::shared_ptr<SubMeshRenderer> RendererManager::GetRendererPtr(const std::string &name) noexcept
{
auto it = RenderersMap.find(name);
if (it != RenderersMap.end())
return it->second;
else
return nullptr;
}
void RendererManager::UseRenderer(std::shared_ptr<SubMeshRenderer> pRenderer)
{
if (pRenderer)
CurrentUsedRenderer = pRenderer;
}
void RendererManager::UseRenderer(const std::string& RenderName)
{
auto pRenderer = GetRendererPtr(RenderName);
if (pRenderer)
{
CurrentUsedRenderer = pRenderer;
}
}
void RendererManager::AddRenderer(std::shared_ptr<SubMeshRenderer> pRenderer) noexcept
{
if (pRenderer)
{
RenderersMap.insert(std::make_pair(pRenderer->GetRendererName(), pRenderer));
}
}
void RendererManager::DeleteRenderer(const std::string &name) noexcept
{
auto it = RenderersMap.find(name);
if (it != RenderersMap.end())
RenderersMap.erase(it);
}
void RendererManager::AddLightToRendererContext(std::vector<std::shared_ptr<LightSource>> Lights, std::shared_ptr<SubMesh> pSubMesh)
{
auto RendererIter = SubMeshRendererBindings.find(pSubMesh);
if (RendererIter != SubMeshRendererBindings.end())
{
auto pRenderer = RendererIter->second;
auto ContextIter = RendererContextsMap.find(pRenderer->GetRendererName());
if (ContextIter != RendererContextsMap.end())
{
ContextIter->second->SetShadingLights(Lights);
}
}
}
void RendererManager::AddSubMeshToRendererContext(std::shared_ptr<SubMesh> pSubMesh)
{
auto RendererBindingIter = SubMeshRendererBindings.find(pSubMesh);
if (RendererBindingIter == SubMeshRendererBindings.end())
return;
auto pSubMeshRenderer = RendererBindingIter->second;
auto SubRendererIter = RendererContextsMap.find(pSubMeshRenderer->GetRendererName());
if (SubRendererIter != RendererContextsMap.end())
{
auto Context = SubRendererIter->second;
Context->AddBindedSubMesh(pSubMesh);
}
else
{
auto Context = NewObject<RendererContext>(pSubMeshRenderer);
Context->AddBindedSubMesh(pSubMesh);
RendererContextsMap.insert(std::make_pair(pSubMeshRenderer->GetRendererName(), Context));
}
}
void RendererManager::ClearRendererContext()
{
RendererContextsMap.clear();
}
void RendererManager::BindMeshRenderer(std::shared_ptr<Mesh> pMesh, std::shared_ptr<SubMeshRenderer> pSubMeshRenderer)
{
if (pMesh)
{
size_t SubMeshCount = pMesh->GetSubMeshCount();
for (size_t Index = 0; Index < SubMeshCount; ++Index)
{
auto pSubMesh = pMesh->GetSubMesh(Index);
BindSubMeshRenderer(pSubMesh, pSubMeshRenderer);
}
}
}
void RendererManager::BindSubMeshRenderer(std::shared_ptr<SubMesh> pSubMesh, std::shared_ptr<SubMeshRenderer> pSubMeshRenderer)
{
if (pSubMesh)
{
SubMeshRendererBindings.insert(std::make_pair(pSubMesh, pSubMeshRenderer));
}
}
void RendererManager::UnBindSubMeshRenderer(std::shared_ptr<SubMesh> pSubMesh, std::shared_ptr<SubMeshRenderer> pSubMeshRenderer)
{
auto Iter = SubMeshRendererBindings.find(pSubMesh);
if (Iter != SubMeshRendererBindings.end())
{
SubMeshRendererBindings.erase(Iter);
}
}
} |
cb1060f617c15b0042169382305253af096ad9c7 | 822ef7eb09761cda682546e1230bda9cead75ec5 | /StampValue.cpp | 0589c1ec052912ca470a86584d87db0b6ff2286d | [] | no_license | Harrychen0314/NOIP | 6530bea8a3c788232daeb6b4568b29ce8c9cb56c | 7c6e949d51428e0f81f788e1b8e7a53568fb1cd3 | refs/heads/master | 2020-03-22T09:33:54.046166 | 2018-07-06T03:27:51 | 2018-07-06T03:27:51 | 139,845,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,551 | cpp | StampValue.cpp | #include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
int *result;
int top=0;
int *top_result;
int choose(int stamp[], int stamp_num, int stamp_max,int money) {
int chose = 0;
int i=0;
if (stamp_max > 0) {
for (i = 0; i < stamp_num; i++) {
choose(stamp, stamp_num, stamp_max-1, money + stamp[chose]);
chose++;
}
}else {
result[money]=1;
money=0;
}
return 0;
}
void judge(int n,int k,int stamp[]){
int i;
stamp[n]=0;
n++;
result=(int*)calloc(n*k+1,sizeof(int));
printf("get data\n");
for(i=0;i<n;i++){
printf("%d ",stamp[i]);
}
printf("\n");
for(i=0;i<=n*k;i++){
result[i]=0;
}
choose(stamp, n, k,0);
for(i=1;i<=n*k;i++){
if(result[i]!=1){
break;
}
}
printf("judge result=%d\n",i-1);
if(i-1>top){
top=i-1;
for(i=0;i<n;i++){
top_result[i]=stamp[i];
}
}
}
int generate(int n,const int k,int stamp_sub,int output[]){
int i=0;
int stamp_value=0;
if(stamp_sub < n){
output[stamp_sub]=stamp_value;
//printf("chose %d\n",stamp_value);
for (i = 0; i <= n+1; i++){
output[stamp_sub]=stamp_value;
//printf("chose %d\n",stamp_value);
generate(n,k,stamp_sub+1,output);
stamp_value++;
}
}else{
judge(n,k,output);
return 0;
}
}
int main(void) {
int n, k;
int i;
scanf("%d", &k);
scanf("%d", &n);
int *stamp = (int*)calloc(k+1, sizeof(int));
top_result=(int*)calloc(n,sizeof(int));
generate(n,k,0,stamp);
for(i=0;i<n;i++){
printf("%d ",top_result[i]);
}
printf("\nMAX=%d\n",top);
system("pause");
return (0);
} |
69564de9267c1f4780aafc222a0fc418733fe939 | abbb67d330dd13dd798e9ec3bee364c652ac8084 | /c++/sort/main.cpp | 33e8a93b22cc563b1c29e0bcd761878d9d42fd27 | [] | no_license | bigobject/cplusplusdemo | 4afa8f2a0d1bbb9c257db1d71b995fd772b13b03 | 6283c39499833acf4d8669e4838ccbe7b804d03e | refs/heads/master | 2022-04-20T04:53:18.941591 | 2020-04-11T03:52:14 | 2020-04-11T03:52:14 | 254,547,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,878 | cpp | main.cpp | #include <iostream>
#include<string.h>
#include <functional>
void printarr(int* input, int len) {
std::cout << "intput:";
for (int i=0; i<len;i++) {
std::cout << input[i] << " ";
}
std::cout << std::endl;
}
void insertsort(int* input, int len);
void quicksort(int* input, int len);
void cmbsort(int* input, int len);
int main(void)
{
int input[] = {10,4,35,25,3,6,4,4,2,5};
auto len = sizeof(input)/sizeof(int);
printarr(input, len);
int *forinsert = new int[len];
memcpy(forinsert, input, sizeof(input));
insertsort(forinsert, len);
printarr(forinsert, len);
delete []forinsert;
int *forquick = new int[len];
memcpy(forquick, input, sizeof(input));
quicksort(forquick, len);
printarr(forquick, len);
delete []forquick;
int *forcmb= new int[len];
memcpy(forcmb, input, sizeof(input));
cmbsort(forcmb, len);
printarr(forcmb, len);
delete []forcmb;
}
void insertsort(int* input, int len){
if (nullptr == input) {
return;
}
for (int i=1; i<len;i++) {
auto target = input[i];
auto j=i-1;
while(j>=0 && target<input[j]) {
auto tmp = input[j];
input[j] = input[j+1];
input[j+1] = tmp;
j--;
}
}
}
void quicksort(int* input, int len){
}
void cmbsort(int* input, int len){
std::function<void(int*, int,int)>cmb;
cmb = [&cmb](int* input, int start,int end) {
if (start >= end) {
return;
}
auto mid = (start+end)/2;
cmb(input, start, mid);
cmb(input, mid+1, end);
auto l = start;
auto r = mid+1;
int* sorted = new int[end-start+1];
auto i=0;
while (l <= mid||r <=end) {
int *k = nullptr;
if (l >mid) {
k = &r;
}else if (r > end) {
k = &l;
}else if (input[l] <= input[r]) {
k = &l;
}else {
k = &r;
}
sorted[i++] = input[*k];
(*k)++;
}
for (auto j=0; j<end-start+1;j++) {
input[start+j] = sorted[j];
}
delete[] sorted;
};
cmb(input, 0, len-1);
} |
8436183e80ba452fb623c30e29f6f0296e085158 | 51bd093a3a4546661da966b4ebfb2f3d10d8a9c8 | /displaystudent.h | 9097179c1960829ab3d95fd44e7c50771c2cdd9a | [] | no_license | brandon-t-nguyen/EM_Scheduler_QT | 26f1bb00a141964243bceb3730adc7b78ea107da | 62bb71e59baf59b70eea6ae8b686168eda5c2075 | refs/heads/master | 2021-05-29T12:09:40.182327 | 2015-08-17T01:43:02 | 2015-08-17T01:43:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | h | displaystudent.h | #ifndef DISPLAYSTUDENT_H
#define DISPLAYSTUDENT_H
#include <QPushButton>
#include "../EM_Scheduler/Scheduler.h"
#include "../EM_Scheduler/Student.h"
namespace Ui {
class DisplayStudent;
}
class DisplayStudent : public QPushButton
{
Q_OBJECT
public:
explicit DisplayStudent(QWidget *parent = 0);
~DisplayStudent();
void init(Student* attachStudent, Scheduler* attachSchedule);
void update(void);
Student* getStudent(void);
private:
Ui::DisplayStudent *ui;
Student* student;
Scheduler* schedule;
};
#endif // DISPLAYSTUDENT_H
|
512da0a05541c95ced62d855bce3bbf0fee16a05 | dadf8e6f3c1adef539a5ad409ce09726886182a7 | /airplay/h/TinyOpenEngine.App.h | 419895c1496842b9324c0bd4c729fbb72ffe2284 | [] | no_license | sarthakpandit/toe | 63f59ea09f2c1454c1270d55b3b4534feedc7ae3 | 196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b | refs/heads/master | 2021-01-10T04:04:45.575806 | 2011-06-09T12:56:05 | 2011-06-09T12:56:05 | 53,861,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | h | TinyOpenEngine.App.h | #pragma once
#include "toeApp.h"
namespace TinyOpenEngine
{
void toeAppInit();
void toeAppTerminate();
} |
0b9f125e518e755247f2c33da62c3b8800a03b5a | e4096f93471163fde6714fa3a30219ac311bde7f | /schema.cpp | a703a9a2f661beae36e815e138d7b35ce699c09c | [
"MIT"
] | permissive | devmentality/bachelors_thesis | 5d8f1c4e7e689406a66a112fe56112ff977537b0 | 11fcd78b2be9b6d50474950cac497a5b2c7ee3dd | refs/heads/master | 2023-06-01T06:03:57.552026 | 2021-06-14T07:08:12 | 2021-06-14T07:08:12 | 352,308,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 667 | cpp | schema.cpp | #include "schema.h"
#include <iostream>
#include <string>
#include "sqlite3.h"
using namespace std;
void TableDescription::BuildColumnsMapping() {
for (const auto& col : pkey_columns) column_by_index[col.index] = col;
for (const auto& col : other_columns) column_by_index[col.index] = col;
}
int TableDescription::ColumnsAmount() {
return pkey_columns.size() + other_columns.size();
}
void Run(sqlite3* db, const string& sql) {
char* zErrMsg = nullptr;
int rc = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &zErrMsg);
if (rc != SQLITE_OK) {
cerr << "SQL error: " << zErrMsg << endl;
sqlite3_free(zErrMsg);
}
}
|
217ccb59f121b7537fadc9394c305eb198af7362 | 42cc5a7b0c95558d0f622f5b4e43926437e11ec5 | /Calculator.cpp | 5274b9d67a7eacd82646e626c8e789b3f9a07ba2 | [] | no_license | manjuhere/OpenGL-Calculator-v1.0 | 4c01665ab136a1edf9957cfc14b241b72e507104 | a307c609056d8d4bf6d49e3697bf181579b7f17d | refs/heads/master | 2020-11-26T19:30:44.191972 | 2015-12-15T06:08:53 | 2015-12-15T06:08:53 | 17,980,963 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,163 | cpp | Calculator.cpp | // Calculator v1.0
// Created by Manjunath Chandrashekar on 21/03/14.
// Copyright (c) 2014 Manjunath Chandrashekar. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
//Type definitions to clear ambiguities
typedef GLfloat point;
typedef int flag;
//A type defined structure to signify status of calculator
typedef struct {
flag currentOperand; //1.Specifies which operand is entered. -0 if first & 1 if second-
flag resultObtained; //2.Specifies if the result is obtained so that it can be displayed
flag operationDone; //3.Specifies if operation is done so that display is no longer updated after that -0 if not done, 1 if done-
flag operandLength; //4.Useful in limiting the calculator to 10 digit operands
flag clearScreen; //5.Useful to clear the screen
flag decimalOperation; //6.Marks operation as decimal. so that decimal point can be used only once.
flag ErrorOccured; //7.If division by zero is attempted, this flag is set to 1
flag turnedON; //8.If calculator is turned on, its set to 1. By default its 0
} status;
//To index 1st & 2nd operands and total expression as well.
int opr1Index = 0, opr2Index = 0, expIndex = 0;
//Designated Initializer to set up a starting status of calculator
status stat = { 0, 0, 0, 0, 0, 0, 0, 0 };
//Strings to hold entered operands and oprtrs
char operand1Str[50], operand2Str[50], resStr[50], totalExp[100], oprtr, **endptr = NULL;
//Operands in strings converted to floats and result of the operation
double tempOperand, operand1, operand2, result = 0;
//Some temporary variables helpful in printing to calculator output
char tempStr[100];
int temp = -2, x = 0;
//specifies starting and ending Y co-ordinates for all buttons.
//Value is changed each time before drawing separate row.
point rowMinY, rowMaxY;
//Font/Text related stuff
typedef enum {
MODE_BITMAP,
MODE_STROKE
} mode_type;
static mode_type mode;
static int font_index;
//Takes 4 points as arguments and draws a polygon using it.
void DrawButton(point p1, point p2, point p3, point p4);
//Calls DrawButtons numerous times to draw all buttons of the calculator
void DrawAllButtons(void);
//To print the given string or character at location (x, y)
void output(int x, int y, char *string);
//Initialize Display and Window.
void init(void);
//Display Callback.
void Display(void);
//Handles Mouse event.
void Mouse(int btn, int state, int x, int y);
//Handles Keyboard event.
void Keys(unsigned char key, int x, int y);
//Scales Window when resized.
void MyReshape(int w, int h);
//Print to calculator output screen
void PrintOutput(void);
//Reconfigure Operands for further operations
void ReconfigureOperands(void);
//Calculate the result from previous operation
void CalculateResult(void);
//Clear the output screen of the calculator display
void ClearEverything(void);
//Read a character and assign it desired operand
void ReadCharacter(const char key);
//Read the operator to perform operation
void ReadOperator(const char key);
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowPosition(100, 100);
glutInitWindowSize(310, 500);
glutCreateWindow("Calculator v1.0");
init();
glutMouseFunc(Mouse);
glutKeyboardFunc(Keys);
glutDisplayFunc(Display);
glutReshapeFunc(MyReshape);
glutMainLoop();
return 0;
}
void DrawButton(point p1, point p2, point p3, point p4) {
glBegin(GL_POLYGON);
glVertex2f(p1, rowMinY);
glVertex2f(p2, rowMinY);
glVertex2f(p3, rowMaxY);
glVertex2f(p4, rowMaxY);
glEnd();
}
void DrawAllButtons(void) {
glColor3f(0.11, 0.11, 0.11);
rowMinY = 15.0, rowMaxY = 70.0; //1st row of buttons
DrawButton(15.0, 70.0, 70.0, 15.0);
glColor3f(0.79, 0.79, 0.79);
DrawButton(90.0, 145.0, 145.0, 90.0);
DrawButton(165.0, 220.0, 220.0, 165.0);
DrawButton(240.0, 295.0, 295.0, 240.0);
rowMinY = 90.0, rowMaxY = 145.0; //2nd row of buttons
DrawButton(15.0, 70.0, 70.0, 15.0);
DrawButton(90.0, 145.0, 145.0, 90.0);
DrawButton(165.0, 220.0, 220.0, 165.0);
DrawButton(240.0, 295.0, 295.0, 240.0);
rowMinY = 165.0, rowMaxY = 220.0; //3rd row of buttons
DrawButton(15.0, 70.0, 70.0, 15.0);
DrawButton(90.0, 145.0, 145.0, 90.0);
DrawButton(165.0, 220.0, 220.0, 165.0);
DrawButton(240.0, 295.0, 295.0, 240.0);
rowMinY = 240.0, rowMaxY = 295.0; //4th row of buttons
DrawButton(15.0, 70.0, 70.0, 15.0);
DrawButton(90.0, 145.0, 145.0, 90.0);
DrawButton(165.0, 220.0, 220.0, 165.0);
DrawButton(240.0, 295.0, 295.0, 240.0);
rowMinY = 315.0, rowMaxY = 370.0; //5th row of buttons
glColor3f(0.94, 0.4, 0.33);
DrawButton(15.0, 70.0, 70.0, 15.0);
DrawButton(90.0, 145.0, 145.0, 90.0);
DrawButton(165.0, 295.0, 295.0, 165.0);
rowMinY = 390, rowMaxY = 485; //Output screen
glColor3f(0.93, 0.98, 0.75);
DrawButton(15.0, 295.0, 295.0, 15.0);
glColor3f(1.0, 1.0, 1.0); //Display each of the button names.
output(25, 25, "0");
output(100, 25, ".");
output(175, 25, "=");
output(250, 25, "+");
output(25, 100, "1");
output(100, 100, "2");
output(175, 100, "3");
output(250, 100, "-");
output(25, 175, "4");
output(100, 175, "5");
output(175, 175, "6");
output(250, 175, "*");
output(25, 250, "7");
output(100, 250, "8");
output(175, 250, "9");
output(250, 250, "/");
output(25, 325, "ON");
output(95, 325, "OFF");
output(215, 325, "AC");
}
void output(int x, int y, char *string) {
int len, i;
glRasterPos2f(x, y);
len = (int)strlen(string);
for (i = 0; i < len; i++) {
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);
}
}
void MyReshape(int w, int h) {
glutReshapeWindow(310, 500);
}
void init(void) {
glClearColor(0.60f, 0.60f, 0.60f, 1.0f); // gray background
glMatrixMode(GL_PROJECTION); // setup viewing projection
glLoadIdentity(); // start with identity matrix
gluOrtho2D(0.0, 310.0, 0.0, 500.0); // setup a 310x500 viewing window
mode = MODE_BITMAP;
font_index = 0;
}
void Display(void) {
glClear(GL_COLOR_BUFFER_BIT);
DrawAllButtons();
if (stat.turnedON) {
PrintOutput();
}
glFlush();
glutSwapBuffers();
}
void Mouse(int btn, int state, int x, int y) {
if (stat.turnedON) {
if (btn == GLUT_LEFT_BUTTON && (x > 15 && x<70) && (y>455 && y<505) && state == GLUT_DOWN) {
ReadCharacter('0');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>90 && x<145) && (y>455 && y<505) && state == GLUT_DOWN) {
if (stat.decimalOperation == 0) {
if (stat.currentOperand == 0) {
stat.operandLength++;
if (stat.operandLength > 10) {
return;
}
operand1Str[opr1Index++] = '.';
stat.decimalOperation = 1;
}
else if (stat.currentOperand == 1) {
stat.operandLength++;
if (stat.operandLength > 10) {
return;
}
operand2Str[opr2Index++] = '.';
stat.decimalOperation = 1;
}
totalExp[expIndex++] = '.';
}
else if (stat.decimalOperation == 1)
return;
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x > 15 && x<70) && (y>380 && y<430) && state == GLUT_DOWN) {
ReadCharacter('1');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>90 && x<145) && (y>380 && y<430) && state == GLUT_DOWN) {
ReadCharacter('2');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>165 && x<220) && (y>380 && y<430) && state == GLUT_DOWN) {
ReadCharacter('3');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>15 && x<70) && (y>305 && y<355) && state == GLUT_DOWN) {
ReadCharacter('4');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>90 && x<145) && (y>305 && y<355) && state == GLUT_DOWN) {
ReadCharacter('5');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>165 && x<220) && (y>305 && y<355) && state == GLUT_DOWN) {
ReadCharacter('6');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>15 && x<70) && (y>230 && y<280) && state == GLUT_DOWN) {
ReadCharacter('7');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>90 && x<145) && (y>230 && y<280) && state == GLUT_DOWN) {
ReadCharacter('8');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>165 && x<220) && (y>230 && y<280) && state == GLUT_DOWN) {
ReadCharacter('9');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>240 && x<295) && (y>455 && y<505) && state == GLUT_DOWN) {
ReadOperator('+');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>240 && x<295) && (y>380 && y<430) && state == GLUT_DOWN) {
ReadOperator('-');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>240 && x<295) && (y>305 && y<355) && state == GLUT_DOWN) {
ReadOperator('*');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>240 && x<295) && (y>230 && y<280) && state == GLUT_DOWN) {
ReadOperator('/');
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x > 165 && x<295) && (y>155 && y<205) && state == GLUT_DOWN) {
//AC is clicked
ClearEverything();
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>165 && x<220) && (y>455 && y < 505) && state == GLUT_DOWN) {
// = is clicked
CalculateResult();
glutPostRedisplay();
}
else if (btn == GLUT_LEFT_BUTTON && (x>90 && x<145) && (y>155 && y<205) && state == GLUT_DOWN) {
exit(0);
}
}
else if (btn == GLUT_LEFT_BUTTON && (x>15 && x<70) && (y>155 && y<205) && state == GLUT_DOWN) {
stat.turnedON = 1;
glutPostRedisplay();
}
}
void Keys(unsigned char key, int x, int y) {
if (stat.turnedON) {
switch (key) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
ReadCharacter(key);
break;
case '.':
if (stat.decimalOperation == 0) {
if (stat.currentOperand == 0) {
stat.operandLength++;
if (stat.operandLength > 10) {
return;
}
operand1Str[opr1Index++] = '.';
stat.decimalOperation = 1;
}
else if (stat.currentOperand == 1) {
stat.operandLength++;
if (stat.operandLength > 10) {
return;
}
operand2Str[opr2Index++] = '.';
stat.decimalOperation = 1;
}
totalExp[expIndex++] = '.';
}
else if (stat.decimalOperation == 1)
return;
break;
case '+':
ReadOperator('+');
break;
case '-':
ReadOperator('-');
break;
case '*':
ReadOperator('*');
break;
case '/':
ReadOperator('/');
break;
case '=':
case 13: //ASCII value of return key
CalculateResult();
break;
case 27: //ASCII value of Escape key
ClearEverything();
break;
default:
printf("Invalid Character Chosen\n");
return;
break;
}
glutPostRedisplay();
}
else
return;
}
void PrintOutput(void) {
glColor3f(0.0f, 0.0f, 0.0f);
if (stat.operationDone != 1) {
glColor3f(0.0, 0.0, 0.0);
temp++;
tempStr[temp] = totalExp[temp];
output(20, 460, tempStr);
}
if (stat.resultObtained) {
if (expIndex > 25)
totalExp[23] = '\0';
output(20, 460, totalExp);
if (stat.ErrorOccured) {
output(20, 400, "Error.");
stat.ErrorOccured = 0;
}
else {
output(20, 400, "= ");
output(35, 400, resStr);
}
}
if (stat.clearScreen) {
rowMinY = 390, rowMaxY = 485;
glColor3f(0.93, 0.98, 0.75);
DrawButton(15.0, 295.0, 295.0, 15.0);
stat.clearScreen = 0;
}
if (stat.turnedON) {
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(15, 390);
glVertex2f(295, 390);
glVertex2f(295, 485);
glVertex2f(15, 485);
glEnd();
}
}
void ReconfigureOperands(void) {
sprintf(operand1Str, "%f", result);
memset(totalExp, '\0', sizeof(totalExp)); //reset totalExp with null string
memset(operand2Str, '\0', sizeof(operand2Str));
strcpy(totalExp, operand1Str);
expIndex = 0, opr1Index = 0, opr2Index = 0;
while (operand1Str[expIndex] != '\0')
expIndex += 1;
opr2Index = 0;
stat.currentOperand = 1;
stat.resultObtained = 1;
stat.operationDone = 1;
stat.decimalOperation = 0;
stat.operandLength = 0;
}
void CalculateResult(void) {
totalExp[expIndex] = '\0';
printf("oprand1 = %s\n", operand1Str);
printf("oprand2 = %s\n", operand2Str);
operand1 = strtod(operand1Str, endptr);
operand2 = strtod(operand2Str, endptr);
switch (oprtr) {
case '+':
result = operand1 + operand2;
sprintf(resStr, "%f", result); //convert double to string
ReconfigureOperands();
printf("%s is the result.\n", resStr);
break;
case '*':
result = operand1 * operand2;
sprintf(resStr, "%f", result);
if (expIndex > 20) {
resStr[22] = '\0';
}
ReconfigureOperands();
printf("%f is the result.\n", result);
break;
case '-':
result = operand1 - operand2;
sprintf(resStr, "%f", result);
ReconfigureOperands();
printf("%f is the result.\n", result);
break;
case '/':
if (operand2 == 0) {
stat.ErrorOccured = 1;
stat.resultObtained = 1;
glutPostRedisplay();
return;
}
result = operand1 / operand2;
sprintf(resStr, "%f", result);
ReconfigureOperands();
printf("%f is the result.\n", result);
break;
default:
printf("Invalid Character Chosen\n");
break;
}
}
void ClearEverything(void) {
printf("AC is selected.\n");
memset(operand1Str, '\0', sizeof(operand1Str)); //reset operand1 with null string
memset(operand2Str, '\0', sizeof(operand2Str)); //reset operand2 with null string
memset(totalExp, '\0', sizeof(totalExp)); //reset the total expression with null string
memset(tempStr, '\0', sizeof(tempStr));
opr1Index = 0; opr2Index = 0, expIndex = 0, temp = -2; //reset index of both operand strings and total expression
stat.currentOperand = 0; //1.Specifies which operand is entered. -0 if first & 1 if second-
stat.resultObtained = 0; //2.Specifies if the result is obtained so that it can be displayed
stat.operationDone = 0; //3.Specifies if operation is done so that display is no longer updated after that -0 if not done, 1 if done-
stat.operandLength = 0; //4.Useful in limiting the calculator to 10 digit operands
stat.clearScreen = 1; //5.Useful to clear the screen
stat.decimalOperation = 0;
printf("Both Operands cleared.\n");
}
void ReadCharacter(const char key) {
if (stat.currentOperand == 0) {
stat.operandLength++;
if (stat.operandLength > 10) {
return;
}
operand1Str[opr1Index++] = key;
}
else if (stat.currentOperand == 1) {
stat.operandLength++;
if (stat.operandLength > 10) {
return;
}
operand2Str[opr2Index++] = key;
}
totalExp[expIndex++] = key;
}
void ReadOperator(const char key) {
if (stat.currentOperand == 0 && stat.operandLength == 0) {
ClearEverything();
return;
}
if (stat.currentOperand == 1 && stat.operandLength > 0) {
return;
}
oprtr = key;
totalExp[expIndex++] = key;
stat.currentOperand = 1;
stat.operandLength = 0;
stat.decimalOperation = 0;
}
|
fc5f3572f707873bcb9185135abd557401cad65e | a2948213e9e92b7e9f3ebda367860fdaf4a821c1 | /UVA/week_11/11561.cpp | a7741b3aee61cdaf7134fe06ff88f0c58e08bd49 | [] | no_license | Hackerifyouwant/APCS | 5a4482e8bb45ef5285e1d67bf3d84499e010d58e | cbc1138fce55143b04aca61ac9f1c8d956e3db89 | refs/heads/master | 2023-08-16T02:31:31.384735 | 2021-10-25T12:20:11 | 2021-10-25T12:20:11 | 259,782,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,351 | cpp | 11561.cpp | #include<iostream>
#include<deque>
#include<vector>
#include<cstring>
#define ll long long
#define endl '\n'
using namespace std;
struct pos{
int x, y;
}start;
int way[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
char map[105][105];
int vis[105][105];
deque<pos> Q;
bool check (int boardH, int boardW, pos T){
return (T.x >= 0 && T.y >= 0 && T.x < boardH && T.y < boardW);
}
int main(){
int W, H;
while(scanf("%d%d", &W, &H) == 2){
int gold = 0;
memset(map, 0, sizeof(map));
memset(vis, 0, sizeof(vis));
for(int i = 0; i < H; i++){
for(int j = 0; j < W; j++){
cin >> map[i][j];
}
}
for(int i = 0; i < H; i++){
for(int j = 0; j < W; j++){
if(map[i][j] == 'P'){
start.x = i;
start.y = j;
}else if(map[i][j] == 'T'){
for(int k = 0; k < 4; k++){
pos nxtmp;
nxtmp.x = i + way[k][0];
nxtmp.y = j + way[k][1];
if(check(H, W, nxtmp)){
if(vis[nxtmp.x][nxtmp.y] == 0){
vis[nxtmp.x][nxtmp.y] = -1;
}
}
}
}
}
}
if(vis[start.x][start.y] == -1){
cout << 0 << endl;
continue;
}
Q.clear();
Q.push_back(start);
vis[start.x][start.y] = 1;
while(!Q.empty()){
pos tmp = Q.front();
Q.pop_front();
for(int i = 0; i < 4; i++){
pos nxtmp = tmp;
nxtmp.x += way[i][0];
nxtmp.y += way[i][1];
//cout << nxtmp.x << " " << nxtmp.y << " " << map[nxtmp.x][nxtmp.y] << " "<< vis[nxtmp.x][nxtmp.y] << endl;
if(check(H, W, nxtmp) && vis[nxtmp.x][nxtmp.y] != 1 && map[nxtmp.x][nxtmp.y] != '#'){
if(vis[nxtmp.x][nxtmp.y] != -1){
Q.push_back(nxtmp);
}
vis[nxtmp.x][nxtmp.y] = 1;
if(map[nxtmp.x][nxtmp.y] == 'G')gold++;
}
}
}
cout << gold << endl;
}
return 0;
}
|
0f2f0cdd493a0c50bef7d331993ac7455bc5ab6f | 7dc11c9d64c7770d92e9bb65f5976da28e2b3f72 | /src/freeness.h | b445b1fe9868e7db8537149d3029e170fc451891 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"Apache-1.1"
] | permissive | DouglasRMiles/QuProlog | 9c4727e365ef8e4ab0c0ef19ece0ee6d7693781f | 798d86f87fb4372b8918ef582ef2f0fc0181af2d | refs/heads/master | 2022-01-24T05:59:01.097944 | 2022-01-06T18:58:38 | 2022-01-06T18:58:38 | 142,097,490 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,205 | h | freeness.h | // freeness.h - has two components:
// a. freeness test returns no, unsure, yes.
// b. applies not_free_in constraints to terms.
//
// ##Copyright##
//
// Copyright 2000-2016 Peter Robinson (pjr@itee.uq.edu.au)
//
// 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.00
//
// 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.
//
// ##Copyright##
//
// $Id: freeness.h,v 1.3 2002/03/13 01:38:25 qp Exp $
#ifndef FREENESS_H
#define FREENESS_H
private:
bool notFreeInStructure(ObjectVariable *, PrologValue&,
bool gen_delays = true);
bool notFreeInList(ObjectVariable *, PrologValue&, bool gen_delays = true);
bool notFreeInQuantifier(ObjectVariable *, PrologValue&,
bool gen_delays = true);
public:
//
// Check whether ObjectVariable is not free in the s*X.
// (X may be a variable or object variable)
//
bool notFreeInVar(ObjectVariable *, PrologValue&, bool gen_delays = true);
//
// Constrain object variable to be not free in the term. Fails if free in.
// Succeeds if not free in. Delays otherwise.
// Delayed not_free_in problems are generated where necessary.
//
bool notFreeIn(ObjectVariable *, PrologValue&, bool gen_delays = true);
//
// Not free in calls generated internally by the system can be of the form
// object_variable not_free_in term with object_variable of the form s*x and
// term having possible free locals.
//
bool internalNotFreeIn(PrologValue object_variable,
PrologValue term);
//
// Simplify the substitution associated with var and apply not free in.
//
bool notFreeInVarSimp(ObjectVariable *, PrologValue&);
//
// Add extra info to all variables appearing in the term.
// This is needed so that when simplifying terms new variables with extra
// info are not produced because, otherwise it will cause problems
// with term copying.
//
void addExtraInfoToVars(Object *term);
//
// Used in simplifying substitutions.
// Do trivial simplifications without resorting to simplify_term.
// "Complicated" constraints are ignored
//
bool notFreeInNFISimp(ObjectVariable*, PrologValue&);
//
// A C-level implementation of freeness_test.
//
truth3 freeness_test(ObjectVariable*, PrologValue&);
//
// freeness_test_quant does the freeness test on a quantified term
//
truth3 freeness_test_quant(ObjectVariable*, PrologValue&);
//
// freeness_test_var does the freeness test on a var term
//
truth3 freeness_test_var(ObjectVariable*, PrologValue&);
//
// freeness_test_obvar does the freeness test on an obvar term
//
truth3 freeness_test_obvar(ObjectVariable*, PrologValue&);
//
// Carry out a quick test to see if an object var is NFI a term.
// USed by dropSub to remove subs where possible.
//
bool fastNFITerm(ObjectVariable*, Object*);
#endif // FREENESS_H
|
d6d09dad8dde322586b2ac0780d18a53fa1660f0 | 5907240a1c23082e614a78dbf085cf21e7ea0e97 | /BoostLibrary/Chapter_10/portable_way_to_export_and_import_functions_and_classes/portable_way_to_export_and_import_functions_and_class.hpp | 8c71e3c38a4d494e5791258968762b765c6c03c7 | [] | no_license | sadaharu-gintama/SomeCode | b742ec44efded16cad32e872a5c3865da1892de4 | fa5361cd0302343208f1ef73acd31947d84a4fb9 | refs/heads/master | 2021-06-16T18:42:56.617939 | 2017-06-05T04:56:08 | 2017-06-05T04:56:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | hpp | portable_way_to_export_and_import_functions_and_class.hpp | // 1. in the header file, we need definitions from the following include header
#include <boost/config.hpp>
// 2. the following code must also be added
#if defined(MY_LIBRARY_LINK_DYNAMIC)
#if defined(MY_LIBRARY_COMPILATION)
#define MY_LIBRARY_API BOOST_SYMBOL_EXPORT
#else
#define MY_LIBRARY_API BOOST_SYMBOL_IMPORT
#endif
#else
#define MY_LIBRARY_API
#endif
// 3. now all the declaration must use the MY_LIBRARY_API macro
int MY_LIBRARY_API foo();
class MY_LIBRARY_API bar {
public:
/*...*/
int meow() const;
};
// 4. exceptions must be declared with BOOST_SYMBOL_VISIBLE. otherwise they can be caught only using catch(...)
#include <stdexcept>
struct BOOST_SYMBOL_VISIBLE bar_exception : public std::exception {};
|
91f1d842cf41cebcf177e09ff8e0802b4f316a38 | 5220ec44bd018f12c32da698cacf8a4ee5108ecf | /Data Structures/Programs/prj2/main.cpp | 9f381f22047ca3dfb5c8b5083ddd4c4dc945993d | [] | no_license | ace0625/school-work | bf994f96a0821aaf6aa73194189a98c8feb96b07 | bf41322ec812924e1d60a26d9378afd28555298d | refs/heads/master | 2021-01-01T03:34:55.865381 | 2016-05-25T21:23:14 | 2016-05-25T21:23:14 | 59,698,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,272 | cpp | main.cpp | //CS163
//Program#2
//Hyunchan Kim
//main.cpp
//This is main file that starts this program
#include "list.h"
#include "queue.h"
#include "stack.h"
int main()
{
product product_list, a_product;
list cart_list;
queue ordered_list;
stack waiting_list;
char file[] = "data.txt";
char pos[10];
int menu; //menu choice
cout << "======================================================================" << endl;
cout << " <Welcome to Kim's AMAZON> " << endl;
cout << "======================================================================" << endl << endl;
do
{
cout << "\n================ MENU ===============" << endl;
cout << "1. Loop up product list" << endl;
cout << "2. Add a product to your shopping cart(list)" << endl;
cout << "3. Display your all item in your cart" << endl;
cout << "4. Order a product(enqueue)" << endl;
cout << "5. Process a product(dequeue)" << endl;
cout << "6. Display your ordered list(in queue)" << endl;
cout << "7. Add to the wating list(push)" << endl;
cout << "8. Loop up the wating list at the top(peek)" << endl;
cout << "9. Remove an item from the wating list(pop)" << endl;
cout << "0. Exit" << endl;
cin >> menu;
switch (menu)
{
case 1:
product_list.readfile(file);
break;
case 2:
cout << "Enter the position you would like to add in your shopping cart: ";
cin >> pos;
product_list.retrieve(pos, file);
if(cart_list.add(product_list))
cout << "Your order has been added in your cart! " << endl;
else
cout << "Cannot find the item " << endl;
break;
case 3:
cout << "\n ============ Your shopping cart list ================" << endl;
if(!cart_list.display_all())
cout << "Your shopping cart is empty" << endl;
break;
case 4:
cout << "Enter the position you would like to order: ";
cin >> pos;
product_list.retrieve(pos, file);
if(ordered_list.enqueue(product_list))
cout << "Your order has been added" << endl;
else
cout << "Cannot find the item " << endl;
break;
case 5:
if(ordered_list.dequeue())
cout << "An order has been processed" << endl;
else
cout << "Cannot process the order" << endl;
break;
case 6:
cout << "\n ============ Your Ordered list ================" << endl;
ordered_list.display_all();
break;
case 7:
cout << "Enter the position number that is out of stock : ";
cin >> pos;
product_list.retrieve(pos, file);
if(waiting_list.push(product_list))
cout << "Your order has been added to the wating list" << endl;
else
cout << "Cannot find the item " << endl;
break;
case 8:
cout << "\n ============ Peek ================" << endl;
waiting_list.peek(a_product);
break;
case 9:
cout << "\n ============ Pop ================" << endl;
if(waiting_list.pop())
cout << "The top item has been removed " << endl;
else
cout << "no item to remove" << endl;
break;
case 0: //exit. see you next time
cout << ">>>>>>>>SEE YOU NEXT TIME!" << endl;
return 0;
break;
}
} while (true);
return 0;
}
|
88562e336a2c6ca93f716d835c32964bd75aaa35 | a7c0067c0f57e053b9208dc306c5046a152ea2d6 | /src/tutorials/Footorial03.cpp | f1d1b1299b4b1f39ba7f41e5241f5217d05cbf71 | [] | no_license | kkeiper1103/cpp-program | 9c01ded7cb5128f244363acf98ed2533ee4bded6 | e18636f7636a40fedd89b0ab8214ee0e820a5ca9 | refs/heads/main | 2023-03-10T01:32:17.928347 | 2021-02-23T21:25:07 | 2021-02-23T21:25:07 | 340,647,967 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,321 | cpp | Footorial03.cpp | /*
* Footorial03.cpp
*
* Created on: Feb 22, 2021
* Author: kkeiper1103
*/
#include "Footorial03.h"
Footorial03::Footorial03() {
// TODO Auto-generated constructor stub
window = SDL_CreateWindow("Footorial 03", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
surface = SDL_GetWindowSurface(window);
}
Footorial03::~Footorial03() {
// TODO Auto-generated destructor stub
SDL_DestroyWindow(window);
}
int Footorial03::run() {
init();
bool quit = false;
SDL_Event e;
currentSurface = keyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT];
while(!quit) {
while(SDL_PollEvent(&e) != 0) {
if(e.type == SDL_QUIT) quit = true;
else if( e.type == SDL_KEYDOWN ) {
switch(e.key.keysym.sym) {
case SDLK_UP:
currentSurface = keyPressSurfaces[KEY_PRESS_SURFACE_UP]; break;
case SDLK_DOWN:
currentSurface = keyPressSurfaces[KEY_PRESS_SURFACE_DOWN]; break;
case SDLK_LEFT:
currentSurface = keyPressSurfaces[KEY_PRESS_SURFACE_LEFT]; break;
case SDLK_RIGHT:
currentSurface = keyPressSurfaces[KEY_PRESS_SURFACE_RIGHT]; break;
default:
currentSurface = keyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT]; break;
}
}
}
SDL_BlitSurface(currentSurface, nullptr, surface, nullptr);
SDL_UpdateWindowSurface(window);
}
close();
return SUCCESS;
}
void Footorial03::init() {
loadMedia();
}
bool Footorial03::loadMedia() {
bool success = true;
// load default
keyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT] = loadSurface("resources/images/press.bmp");
keyPressSurfaces[KEY_PRESS_SURFACE_UP] = loadSurface("resources/images/up.bmp");
keyPressSurfaces[KEY_PRESS_SURFACE_DOWN] = loadSurface("resources/images/down.bmp");
keyPressSurfaces[KEY_PRESS_SURFACE_LEFT] = loadSurface("resources/images/left.bmp");
keyPressSurfaces[KEY_PRESS_SURFACE_RIGHT] = loadSurface("resources/images/right.bmp");
return success;
}
void Footorial03::close() {
for(unsigned i=0; i < sizeof(keyPressSurfaces) / sizeof(SDL_Surface*); ++i) {
SDL_FreeSurface(keyPressSurfaces[i]);
}
}
SDL_Surface* Footorial03::loadSurface(const std::string &path) {
SDL_Surface* surface = SDL_LoadBMP(path.c_str());
if(surface == nullptr)
std::cerr << "Error Loading Image: " << path.c_str() << '\t' << SDL_GetError() << std::endl;
return surface;
}
|
68875ae873e0eb107deef20a2441ae667786f02b | 61a344bd2ae94057a3cd0f53f850af918baa2f56 | /dBOSpp/dBOS_Queue.cpp | 170a5e7a2a8d47db39579e8285d213ead7a8b022 | [] | no_license | yisea123/dBOS | 18435199775de7931061ad29989c0535738b0f68 | e23c5c6b9a00dfe6504910b05a0ce89fa39d603d | refs/heads/master | 2020-09-21T16:22:23.322436 | 2016-07-14T08:46:58 | 2016-07-14T08:46:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,793 | cpp | dBOS_Queue.cpp | /**
* @file dBOS_Queue.cpp
* @author David Broadhurst
* @date 15/11/2015
*
* \brief Implementation of dBOS Queue.
*
*/
// -------------------------------------------------------------------------------------------------
// INCLUDE FILES
#include "dBOS_Queue.hpp"
#include "dBOS_Port.hpp"
#include "dBOS_DebugPrint.hpp"
#include "dBOS_Assert.hpp"
#include <string.h>
namespace dBOS {
// -------------------------------------------------------------------------------------------------
// LOCAL DEFINES
// -------------------------------------------------------------------------------------------------
// LOCAL CONSTANTS
// -------------------------------------------------------------------------------------------------
// LOCAL DATA TYPES
// -------------------------------------------------------------------------------------------------
// LOCAL TABLES
// -------------------------------------------------------------------------------------------------
// LOCAL VARIABLES
// -------------------------------------------------------------------------------------------------
// LOCAL VARIABLES SHARED WITH INTERRUPT SERVICE ROUTINES
// -------------------------------------------------------------------------------------------------
// LOCAL FUNCTION PROTOTYPES
// -------------------------------------------------------------------------------------------------
// PUBLIC FUNCTIONS
dBOS_QUEUE::dBOS_QUEUE(DBOS_ID_t const ID, UNATIVECPU_t const Size, UNATIVECPU_t const ItemSize) :
dBOS_BASE(ID), m_Size(Size), m_ItemSize(ItemSize), m_ISRMask(ISRMASK_NONE), m_QueueSpace(NULLPTR), m_Level(0U), m_Wpnt(0U), m_Rpnt(0U){
m_QueueSpace = new INT8U[Size * ItemSize];
}
dBOS_QUEUE::dBOS_QUEUE(DBOS_ID_t const ID, UNATIVECPU_t const Size, UNATIVECPU_t const ItemSize, INTERRUPT_MASK_t const Mask) :
dBOS_BASE(ID), m_Size(Size), m_ItemSize(ItemSize), m_ISRMask(Mask), m_QueueSpace(NULLPTR), m_Level(0U), m_Wpnt(0U), m_Rpnt(0U){
m_QueueSpace = new INT8U[Size * ItemSize];
}
dBOS_QUEUE::~dBOS_QUEUE(void){
}
DBOS_RESULT_t dBOS_QUEUE::WriteToBack(void const * const pData){
ASSERT_FROM_OSCS(DBOS_Port_CheckCurrentMaskLevel(m_ISRMask) == TRUE)
DBOS_RESULT_t Result;
if(m_Level < m_Size){
INT8U * const pnt = m_QueueSpace + (m_Wpnt * m_ItemSize);
memcpy(pnt, pData, m_ItemSize);
m_Level++;
m_Wpnt++;
if(m_Wpnt >= m_Size){
m_Wpnt = 0U;
}
Result = DBOS_Q_WRITTEN;
}
else{
Result = DBOS_Q_WRITE_FAIL_FULL;
}
return Result;
}
DBOS_RESULT_t dBOS_QUEUE::WriteToFront(void const * const pData){
ASSERT_FROM_OSCS(DBOS_Port_CheckCurrentMaskLevel(m_ISRMask) == TRUE)
DBOS_RESULT_t Result;
if(m_Level < m_Size){
if(m_Rpnt == 0U){
m_Rpnt = m_Size - 1U;
}
else{
m_Rpnt--;
}
INT8U * const pnt = m_QueueSpace + (m_Rpnt * m_ItemSize);
memcpy(pnt, pData, m_ItemSize);
m_Level++;
Result = DBOS_Q_WRITTEN;
}
else{
Result = DBOS_Q_WRITE_FAIL_FULL;
}
return Result;
}
DBOS_RESULT_t dBOS_QUEUE::ReadFromFront(void * const pData){
ASSERT_FROM_OSCS(DBOS_Port_CheckCurrentMaskLevel(m_ISRMask) == TRUE)
DBOS_RESULT_t Result;
if(m_Level > 0U){
INT8U * const pnt = m_QueueSpace + (m_Rpnt * m_ItemSize);
memcpy(pData, pnt, m_ItemSize);
m_Level--;
m_Rpnt++;
if(m_Rpnt >= m_Size){
m_Rpnt = 0U;
}
Result = DBOS_Q_READ;
}
else{
Result = DBOS_Q_READ_FAIL_EMPTY;
}
return Result;
}
DBOS_RESULT_t dBOS_QUEUE::ReadFromBack(void * const pData){
ASSERT_FROM_OSCS(DBOS_Port_CheckCurrentMaskLevel(m_ISRMask) == TRUE)
DBOS_RESULT_t Result;
if(m_Level > 0U){
if(m_Wpnt == 0U){
m_Wpnt = m_Size - 1;
}
else{
m_Wpnt--;
}
INT8U * const pnt = m_QueueSpace + (m_Wpnt * m_ItemSize);
memcpy(pData, pnt, m_ItemSize);
m_Level--;
Result = DBOS_Q_READ;
}
else{
Result = DBOS_Q_READ_FAIL_EMPTY;
}
return Result;
}
UNATIVECPU_t dBOS_QUEUE::GetLevel(void) const{
ASSERT_FROM_OSCS(DBOS_Port_CheckCurrentMaskLevel(m_ISRMask) == TRUE)
return m_Level;
}
INTERRUPT_MASK_t dBOS_QUEUE::GetISRMask(void) const{
return m_ISRMask;
}
#if (DBOS_DEBUGOUTPUTENABLED == 1U)
void dBOS_QUEUE::PrintDetails() const{
this->PrintTypeAndID();
DBOS_Intprintf("\n Depth: %i", m_Size);
DBOS_Intprintf("\n Current Level: %i", m_Level);
DBOS_Intprintf("\n Item Size: %i Bytes", m_ItemSize);
}
void dBOS_QUEUE::PrintTypeAndID() const{
DBOS_Intprintf("Queue: ");
this->PrintID();
}
#endif
// -------------------------------------------------------------------------------------------------
// PROTECTED FUNCTIONS
// -------------------------------------------------------------------------------------------------
// PRIVATE FUNCTIONS
// -------------------------------------------------------------------------------------------------
// INTERRUPT SERVICE ROUTINES
}// namespace
|
f3b885d681b004982ea03442a9f1221c31f7a489 | ec4fdc9d42991a456dfd2b9b1fcfe12e1a9543ae | /src/User/Special/SmallFire.cpp | 8962aed780fa50b71d3a689d1b2a662606463d92 | [] | no_license | yumayo/KarakuriNinja | 43ad73c4df556aaa16d7118e255f0b29495e3fdf | a010913356aacf794e7761db64208ea7742a42d3 | refs/heads/master | 2020-07-16T15:06:43.452503 | 2016-11-16T18:35:43 | 2016-11-16T18:35:43 | 73,949,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | cpp | SmallFire.cpp | #include"SmallFire.h"
void SmallFire::update()
{
count++;
}
void SmallFire::draw()
{
//Vec2f size = Vec2f(100, 100);
//gl::pushModelView();
//gl::translate(Vec2f(app::getWindowWidth() / 2, app::getWindowHeight() / 2 + 50));
//gl::scale(Vec2f(size.x / (image.getSize().x/8.f),size.y / image.getSize().y));
//cinder::gl::color(cinder::ColorA(1, 1, 1, 1));
//int countspeed = 2;
//int index = (count / countspeed) % 8;
//float start_x = (index % 8)*(image.getSize().x / 8.f);
//cinder::gl::draw(image,
// cinder::Area(0, start_y, bigfiretex_.getSize().x, start_y + int(bigfiretex_.getSize().y / 8)),
// cinder::Rectf(-bigfiresize / 2, bigfiresize / 2));
//gl::popModelView();
}
|
21779f899eb20bdf98ed115c0599bc3838989682 | 7f2255fd0fce35a14556dda32ff06113c83b2e88 | /HDUOJ/hdu4268.cpp | 4832f5eb81289cdeaa60511d5f0dee2a81827040 | [] | no_license | cordercorder/ProgrammingCompetionCareer | c54e2c35c64a1a5fd45fc1e86ddfe5b72ab0cb01 | acc27440d3a9643d06bfbfc130958b1a38970f0a | refs/heads/master | 2023-08-16T18:21:27.520885 | 2023-08-13T15:13:44 | 2023-08-13T15:13:44 | 225,124,408 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,507 | cpp | hdu4268.cpp | #include<bits/stdc++.h>
using namespace std;
#define FC ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define FIN freopen("in.txt","r",stdin)
#define FOUT freopen("out.txt","w",stdout)
#define deb(x) cerr<<"DEBUG------"<<'\n';cerr<<#x<<"------>";err(x)
template<typename T>
void err(T a){
cerr<<a<<'\n';
cerr<<"END OF DEBUG"<<'\n'<<'\n';
}
const long double PI=acos(-1.0);
const long double eps=1e-6;
const long long maxw=(long long)1e17+(long long)10;
using ll=long long;
using ull=unsigned long long;
using pii=pair<int,int>;
/*head------[@cordercorder]*/
const int maxn=(int)1e5+10;
int T;
int n;
pii A[maxn],B[maxn];
bool cmp(const pii &a,const pii &b){
return a.first<b.first;
}
void solve(){
sort(A+1,A+1+n,cmp);
sort(B+1,B+1+n,cmp);
multiset<int> s;
int i,j,ans=0;
for(i=1,j=1;i<=n;i++){
while(j<=n&&A[i].first>=B[j].first){
s.insert(B[j].second);
j++;
}
if(!s.empty()){
multiset<int>::iterator it=s.upper_bound(A[i].second);
if(it!=s.begin()){
it--;
s.erase(it);
ans++;
}
}
}
printf("%d\n",ans);
}
int main(void){
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d %d",&A[i].first,&A[i].second);
}
for(int i=1;i<=n;i++){
scanf("%d %d",&B[i].first,&B[i].second);
}
solve();
}
return 0;
}
|
fa3e4216d07342484e02d515f830591662d9a479 | 5be3bd4247e68be89eaf19f7cfecebecb5ba8420 | /Bar/bar.cpp | 5f2c639d442b1c2ddff4c046ae8159f3c24b80ab | [] | no_license | TiagoPinto/Bar | 14c7007f1f83c07ce7d2881a7b4860991337051a | dbed5f0fe0aa9c9108ff1593d0e0e0650f43b0e7 | refs/heads/master | 2021-01-01T06:26:17.234044 | 2013-06-03T23:51:51 | 2013-06-03T23:51:51 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 11,375 | cpp | bar.cpp | #include "includes.h"
#include "bar.h"
#include "plano.h"
#include "cubo.h"
#include "copo.h"
#include "CadeiraBanco.h"
#include "CadeiraComprido.h"
#include "CadeiraRei.h"
#include "cadeiraStandart.h"
#include "CandeeiroCandelabro.h"
#include "CandeeiroParede.h"
#include "CandeeiroMesa.h"
#include "MesaRectangular.h"
#include "MesaRedonda.h"
#include "MesaStandart.h"
#include "balcao.h"
/**
* Construtor da class Bar.
* Simplesmente inicializa as variaveis de instancia.
*
*/
Bar::Bar(){
this->c = 0.0f;
this->l = 0.0f;
this->a = 0.0f;
this->f = 0.0f;
this->p = 0.0f;
}
/**
* Construtor da class Bar.
* Simplesmente inicializa as variaveis de instancia.
* @param c
* Define o comprimento do espaço
* @param l
* define a largura do espaço
* @param a
* define a altura do espaço
* @param f
* define as fatias do espaço
* @param p
* define as camadas do espaco
*/
Bar::Bar(float c, float l, float a, float f, float p){
this->c = c;
this->l = l;
this->a = a;
this->f = f;
this->p = p;
float comp = this->c/2;
float larg = this->l/2;
float alt = this->a/2;
//TEXTURAS
GLuint texparede = getTextura("texturas/paredes.jpg");
GLuint textecto = getTextura("texturas/cena.jpg");
GLuint texchao = getTextura("texturas/chao.png");
GLuint ferro = getTextura("texturas/ferro.jpg");
GLuint vela = getTextura("texturas/vela.jpg");
GLuint madeira = getTextura("texturas/madeira.jpg");
GLuint madeira5 = getTextura("texturas/madeirinha.jpg");
GLuint madeira4 = getTextura("texturas/madeira7.jpg");
GLuint mobilia = getTextura("texturas/mobilia.jpg");
GLuint porta = getTextura("texturas/porta.jpg");
GLuint vidro = getTextura("texturas/vidro.jpg");
GLuint tapete = getTextura("texturas/tapete2.jpg");
GLuint espadarei = getTextura("texturas/espadaRei.jpg");
GLuint metal = getTextura("texturas/metal.jpg");
GLuint ouro = getTextura("texturas/ouro.jpg");
//GLuint aranha = getTextura("texturas/aranhico.jpg");
/*Desenha o Chao do bar */
chaoP = new Plano(comp, 2*larg / 3, this->f, this->p,2, texchao);
chaoC = new Cubo(6 * comp / 8, 0.05f, 1*larg / 3, this->f, this->p, texchao);
/*Desenha as Paredes do Bar*/
parede[0] = new Plano(6*comp/8, alt, this->f, this->p,1, texparede);
parede[1] = new Plano(comp, alt, this->f, this->p,1, texparede);
parede[2] = new Plano(larg, alt, this->f, this->p,1, texparede);
parede[3] = new Plano(2*larg/3, alt, this->f, this->p,1, texparede);
parede[4] = new Plano(larg/3, alt, this->f, this->p,1, texparede);
parede[5] = new Plano(2*comp/8, alt, this->f, this->p,1, texparede);
/*Desenha o Chao do bar */
tecto[0] = new Plano(comp, 2*larg / 3, this->f, this->p,2, textecto);
tecto[1] = new Plano(6 * comp / 8, 1*larg / 3, this->f, this->p,2, textecto);
/*Pilares */
pilares[0] = new Cubo(0.1, alt, 0.1, f, p, madeira);
/*Candeeiros*/
candeeiroTecto[0] = new CandeeiroCandelabro(larg/35,1.5*alt/4, f, p, ferro, vela, madeira);
candeeiroTecto[0]->preparaB();
candeeiroTecto[1] = new CandeeiroCandelabro(0.2,alt/4, f, p, ferro, vela, madeira);
candeeiroTecto[1]->preparaB();
candeeiroParede[0] = new CandeeiroParede(0.09f,0.15f,f,p, madeira, vidro, vela);
candeeiroMesa[0] = new CandeeiroMesa(0.05,0.2,f,p,ferro, vela);
/*MESAS*/
mesaRedonda[0] = new MesaRedonda(0.7,2.0,alt/4, 0.04, f, p, mobilia);
mesaRectangular[0] = new MesaRectangular(comp/3,0.5, alt/4,0.05, f, p, mobilia);
/*CADEIRA*/
cadeiracomprido[0] = new CadeiraComprido(comp/7, 0.17, alt/4, 0.01, f, p, mobilia);
cadeiraRei = new CadeiraRei(0.35f, 0.3f, alt/2, 0.05f, f, p, mobilia, ferro);
banco = new CadeiraBanco(0.1, 0.09, alt/7, 0.01, f, p, madeira5);
cadeiraStandart = new CadeiraStandart(0.20f, 0.18f, alt/3, 0.02f, f, p, mobilia);
/* Balcao */
balcao = new Balcao(0.3f,comp/5, alt/3, f*2, c, madeira4, vidro, metal);
/*ENFEITES*/
enfeites[0] = new Plano(1.5f, 2*alt/3-0.05f, 1, 1, 1, porta);
enfeites[1] = new Plano((6*comp/8)/2, larg/6, f, c, 2, tapete);
enfeites[2] = new Plano(0.1f, 0.5f, 1, 1, 1, espadarei);
//enfeites[3] = new Plano(1.5, alt/3, 1, 1, 1, aranha);
/*COPOS*/
caneca = new Copo(0.03, 0.06, 0.001, f, c, 2, metal);
copo = new Copo(0.02, 0.04, 0.001, f, c, 1, ouro);
}
/**
* Desenha as 4 paredes, o chão e o tecto.
*
*/
void Bar::desenha(){
float comp = this->c/2;
float larg = this->l/2;
float alt = this->a/2;
/*Desenha o Chao do bar */
glPushMatrix();
glTranslatef(0, 0,1* larg / 6);
chaoP->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(- comp / 8, 0.05/2,-larg / 3);
chaoC->desenha();
glPopMatrix();
/*Desenha as Paredes do Bar*/
glPushMatrix();
glTranslatef(-comp/8, alt/2, -larg/2);
parede[0]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(0, alt/2, larg/2);
glRotatef(180,0,1,0);
parede[1]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/2,alt/2,0);
glRotatef(90,0,1,0);
parede[2]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/2,alt/2,larg/6);
glRotatef(-90,0,1,0);
parede[3]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4,alt/2,-larg/3);
glRotatef(-90,0,1,0);
parede[4]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4 + comp/8,alt/2,-larg/6);
parede[5]->desenha();
glPopMatrix();
/*Desenha o Tecto do bar */
glPushMatrix();
glTranslatef(0, alt,1* larg / 6);
glRotatef(180,1,0,0);
tecto[0]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(- comp / 8, alt,-1* larg / 3);
glRotatef(180,1,0,0);
tecto[1]->desenha();
glPopMatrix();
/* PILARES */
glPushMatrix();
glTranslatef(-3 * comp / 8, alt/2+0.025, -larg / 6-0.05);
pilares[0]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/8, alt/2+0.025, -larg / 6-0.05);
pilares[0]->desenha();
glPopMatrix();
/*------------------------------------DESENHA OS CANDEEIROS------------------------------------------ */
glPushMatrix();
glTranslatef(-comp/8, alt-(1.5*alt)/8,0);
candeeiroTecto[0]->desenhaB();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/8, alt-alt/8,larg/3);
candeeiroTecto[1]->desenhaB();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/8, alt-alt/8,-larg/3);
candeeiroTecto[1]->desenhaB();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/2+0.06, 2*alt/3,-larg/3);
glRotatef(90,0,1,0);
candeeiroParede[0]->desenhaA();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/2+0.06, 2*alt/3,larg/3);
glRotatef(90,0,1,0);
candeeiroParede[0]->desenhaA();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/2-0.06, 2*alt/3,larg/3);
glRotatef(-90,0,1,0);
candeeiroParede[0]->desenhaA();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4-0.06, 2*alt/3,-larg/3);
glRotatef(-90,0,1,0);
candeeiroParede[0]->desenhaA();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, alt/4+0.1,larg/6);
candeeiroMesa[0]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/4, alt/4+0.1,larg/6);
candeeiroMesa[0]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4+0.5, alt/4+0.1,larg/3+0.5);
candeeiroMesa[0]->desenha();
glPopMatrix();
/*---------------------------------------DESENHA AS MESAS-----------------------------------------*/
glPushMatrix();
glTranslatef(comp/4+0.5, 0.0f,larg/3+0.5);
mesaRedonda[0]->desenhaB();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 0.0f,larg/6);
glRotatef(90,0,1,0);
mesaRectangular[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/4, 0.0f,larg/6);
glRotatef(90,0,1,0);
mesaRectangular[0]->desenhaC();
glPopMatrix();
/*---------------------------------------DESENHA AS CADEIRAS-----------------------------------------*/
glPushMatrix();
glTranslatef(-comp/4-0.4, 0.0f,larg/9);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/4-0.4, 0.0f,larg/9+comp/7+larg/36);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/4+0.4, 0.0f,larg/9+comp/7+larg/36);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/4+0.4, 0.0f,larg/9);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(0.4, 0.0f,larg/9+comp/7+larg/36);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(0.4, 0.0f,larg/9);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.4, 0.0f,larg/9+comp/7+larg/36);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.4, 0.0f,larg/9);
glRotatef(90,0,1,0);
cadeiracomprido[0]->desenhaC();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/8, 0.0f,-larg/2+0.15);
cadeiraRei->desenhaD();
glPopMatrix();
glPushMatrix();
glTranslatef(alt/14, 0.09f,-0.09f*2);
glRotatef(90,1,0,0);
glRotatef(90,0,0,1);
banco->desenhaB();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4+0.2, 0.0f,larg/3+0.7);
glRotatef(90,0,1,0);
cadeiraStandart->desenhaA();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4+0.2+0.7, 0.0f,larg/3+0.7);
glRotatef(-90,0,1,0);
cadeiraStandart->desenhaA();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4+0.2+0.7, 0.0f,larg/3+0.3);
glRotatef(-90,0,1,0);
cadeiraStandart->desenhaA();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4+0.2, 0.0f,larg/3+0.3);
glRotatef(90,0,1,0);
cadeiraStandart->desenhaA();
glPopMatrix();
/*---------------------------------------DESENHA O BALCAO--------------------------------------------*/
glPushMatrix();
glTranslatef(comp/4+0.3, alt/8,-larg/15);
balcao->desenha();
glPopMatrix();
/*---------------------------------------DESENHA OS ENFEITES-----------------------------------------*/
glPushMatrix();
glTranslatef(-comp/8, alt/3,larg/2-0.1f);
glRotatef(180,0,1,0);
enfeites[0]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/8, 0.06f,-larg/3);
enfeites[1]->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/8+0.28, 0.27f,-larg/2+0.01);
glRotatef(20,0,0,1);
enfeites[2]->desenha();
glPopMatrix();
/*--------------------------------------------DESENHA OS COPOS --------------------------------------------------*/
glPushMatrix();
glTranslatef(-comp/4+0.15, alt/4+0.03,larg/6+0.3);
caneca->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(-comp/4-0.15, alt/4+0.03,larg/6+1);
caneca->desenha();
glPopMatrix();
glPushMatrix();
glTranslatef(comp/4+0.5+0.2, alt/4+0.02,larg/3+0.5+0.2);
copo->desenha();
glPopMatrix();
}
/**
* Destrutor da class Bar.
* * Destroi o VBO criado, para nao ficar alocada memoria na placa grafica
*/
Bar::~Bar(){
glDeleteBuffers(1,&vbo);
delete tecto[0];
delete tecto[1];
delete chaoP;
delete chaoC;
delete parede[0];
delete parede[1];
delete parede[2];
delete parede[3];
delete parede[4];
delete parede[5];
delete candeeiroTecto[0];
delete candeeiroTecto[1];
delete candeeiroMesa[0];
delete candeeiroParede[0];
delete mesaRedonda[0];
delete mesaRectangular[0];
delete enfeites[0];
delete enfeites[1];
delete enfeites[2];
delete enfeites[3];
delete enfeites[4];
delete cadeiracomprido[0];
delete cadeiraRei;
delete cadeiraStandart;
delete copo;
delete caneca;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.