blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
e856cd879fd40d0c6a6442543da396a16957bfc5
9aff82391d50b373e7209423460606b7f8dc83db
/Funciones/Random/cambio_justo.cpp
700666f4ccfd9504096f137c025d9550581d6aaa
[]
no_license
undefinedfceia/guardian-tortuga
2f0630f842904c3b81afe76b0d56a1ecb35c52c3
200e3a3302e8384301d6c3cee23e1b545526a17a
refs/heads/master
2021-07-04T01:33:34.166916
2021-07-03T18:47:11
2021-07-03T18:47:11
203,363,020
0
0
null
null
null
null
UTF-8
C++
false
false
190
cpp
int solution(int n, int coins[], int i) { if (n == 0) return 0; if (coins[i] > n) return solution(n, coins, i - 1); return 1 + solution(n - coins[i], coins, i); }
[ "undefined.fceia@gmail.com" ]
undefined.fceia@gmail.com
beaefe0d88400c666fc3b296fddb4530637d0dba
245b3fdec9d7778c2d5322548db64421be6d9b2e
/Config.ino
8850a11268395cd4789fb2e1430ce85b59c36dba
[]
no_license
choopk/irblaster
c67256f739cefe708be4380685c2bc071cd11fed
7d270e728dc5ed3ebf32accffd90b1a084ab5a28
refs/heads/master
2020-03-29T02:07:26.096997
2018-09-19T08:55:18
2018-09-19T08:55:18
149,421,424
0
0
null
null
null
null
UTF-8
C++
false
false
5,202
ino
#include "Config.h" //Loading client file void Config::loadClientID(){ if (SPIFFS.exists("/clientID.json")) { //file exists, reading and loading Serial.println("reading clientID file"); File clientIDFile = SPIFFS.open("/clientID.json", "r"); if (clientIDFile) { Serial.println("opened clientID file"); size_t size = clientIDFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); clientIDFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { Serial.println("\nparsed json"); json.printTo(Serial); Serial.println("setting custom clientID"); strcpy(clientID, json["clientID"]); strcpy(newHostName, json["hostID"]); strcpy(device_id, json["deviceID"]); } else { Serial.println("failed to load json clientID"); } } } } //Loading network settings void Config::loadIp() { if (SPIFFS.exists("/ip.json")) { //file exists, reading and loading Serial.println("reading ip file"); File ipFile = SPIFFS.open("/ip.json", "r"); if (ipFile) { Serial.println("opened ip file"); size_t size = ipFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); ipFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { Serial.println("\nparsed json"); json.printTo(Serial); Serial.println("setting custom network settings"); strcpy(ip1,json["ip1"]); strcpy(ip2,json["ip2"]); strcpy(ip3,json["ip3"]); strcpy(ip4,json["ip4"]); strcpy(gw1,json["gw1"]); strcpy(gw2,json["gw2"]); strcpy(gw3,json["gw3"]); strcpy(gw4,json["gw4"]); strcpy(sn1,json["sn1"]); strcpy(sn2,json["sn2"]); strcpy(sn3,json["sn3"]); strcpy(sn4,json["sn4"]); } else { Serial.println("failed to load json ip"); } } } } //Loading Wifi settings void Config::loadWifi() { if (SPIFFS.exists("/wifi.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = SPIFFS.open("/wifi.json", "r"); if (configFile) { Serial.println("opened wifi file"); size_t size = configFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { Serial.println("\nparsed json"); json.printTo(Serial); Serial.println("setting custom wifi settings"); strcpy(ssid, json["ssid"]); strcpy(password, json["password"]); } else { Serial.println("failed to load json wifi"); } } wd_timer_id = timer.setInterval((Interval*1000), repeatCT); } } //Load Logging interval void Config::loadInterval() { if (SPIFFS.exists("/interval.json")) { //file exists, reading and loading Serial.println("reading interval file"); File intervalFile = SPIFFS.open("/interval.json", "r"); if (intervalFile) { Serial.println("opened interval file"); size_t size = intervalFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); intervalFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { Serial.println("\nparsed json"); json.printTo(Serial); Serial.println("setting interval settings"); Interval = json["Interval"]; } else { Serial.println("failed to load json wifi"); } } } } void Config::loadMqtt() { if (SPIFFS.exists("/Mqtt.json")) { //file exists, reading and loading Serial.println("reading mqtt file"); File mqttFile = SPIFFS.open("/Mqtt.json", "r"); if (mqttFile) { Serial.println("opened mqtt file"); size_t size = mqttFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); mqttFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { Serial.println("\nparsed json"); json.printTo(Serial); Serial.println("setting mqtt settings"); strcpy(port,json["port"]); strcpy(broker, json["broker"]); } else { Serial.println("failed to load json mqtt"); } } } }
[ "choopk1994@gmail.com" ]
choopk1994@gmail.com
b51559e85161609becd0ee4c67876779939ed24b
41e21884c745697d472d29da596c5c0e9abf438e
/proj05/proj05_functions.cpp
513e4aeb4b421f405097a382d01b3ae0dec0e208
[]
no_license
himsangseung/C-Projects
8c543c3f795143dac52827f1b2a014e059c9a07b
bd76748f92ffdc2ca0347ff3f7365c02acfc19fa
refs/heads/master
2020-05-31T21:33:39.526206
2019-06-06T02:30:48
2019-06-06T02:30:48
190,500,529
0
0
null
null
null
null
UTF-8
C++
false
false
5,299
cpp
/* proj05 : THe Playfair Algorithm section 3 10/15/2018 using five functions with keyword and the plain text, it is to obtain encrypted keyword printed out */ #include "proj05_functions.h" //was used to reference header to test functions string prepare_plaintext(const string &s){ /* takes in a string, and put strips off all but lowercase alphabets, if length of the string is odd, add on character 'x' */ string plain_text = ""; string::size_type d = s.size(); for(string::size_type i = 0; i< d ; i++){ if (isalpha(s[i])){ if (tolower(s[i]) == 'j') {continue;} else if (s[i] == plain_text.back()) {plain_text.push_back('x');} else plain_text += tolower(s[i]); } } if ((plain_text.size()) %2 !=0){ plain_text.push_back('x'); } return plain_text; } string create_encoding(const string &key){ /* takes in the keyword and putting in the form that can symbolize 2-D form. it has length of 25 with 5x5 representative matrix */ string key_square; for (auto charac: key){ if (key_square.find(charac) == string::npos){ key_square += charac; } } for (auto characs: alphabet_minus_j){ if (key_square.find(characs) == string::npos){ key_square.push_back(characs); } } return key_square; } string encode_pair(const string &pr, const string &key){ /* with two characters to be encoded using encoding 2-D matrix, some vairables for indexes are defined each for better readability */ string en_pair; int index_1 = key.find(pr[0]); int index_2 = key.find(pr[1]); int row_1 = index_1 / dim; int row_2 = index_2 / dim; int col_1 = index_1 % dim; int col_2 = index_2 % dim; if (col_1 == col_2){// same column if (row_1 == dim-1){ en_pair.push_back(key[col_1]); } else {en_pair.push_back(key[index_1+dim]);} if (row_2 == dim-1){ // 4 en_pair.push_back(key[col_2]); } else{en_pair.push_back(key[index_2+dim]);} } else if (row_1 == row_2) { //same row if (col_1 == dim-1){ en_pair.push_back(key[row_1*5]); } else {en_pair.push_back(key[index_1+1]);} if (col_2 == dim-1 ){ //4 en_pair.push_back(key[row_2*5]);} else{en_pair.push_back(key[index_2+1]);} } else { int new_index_1 = row_1*5 + col_2; int new_index_2 = row_2*5 + col_1; en_pair.push_back(key[new_index_1]); en_pair.push_back(key[new_index_2]); } return en_pair; } string decode_pair(const string &pr, const string &key){ /* opposite to encode_pair, takes in encoded, two-character input and uses key block matrix to print out original, decoded version of the pair */ string de_pair; int index_1 = key.find(pr[0]); int index_2 = key.find(pr[1]); int row_1 = index_1 / dim; int row_2 = index_2 / dim; int col_1 = index_1 % dim; int col_2 = index_2 % dim; if (col_1 == col_2){// same column if(row_1 == dim-5){ de_pair.push_back(key[(dim-1)*dim + col_1]); de_pair.push_back(key[index_2-dim]); } else{ de_pair.push_back(key[index_1-dim]); if(row_2 ==dim -5){ de_pair.push_back(key[(dim-1)*dim+col_2]); } else{de_pair.push_back(key[index_2-dim]);} } } else if (row_1 == row_2){ // same row if (col_1 == dim-5){ de_pair.push_back(key[row_1*dim+(dim-1)]); de_pair.push_back(key[index_2-1]); } else{ de_pair.push_back(key[index_1-1]); if (col_2 == dim-5){ de_pair.push_back(key[row_2*dim+(dim-1)]); } else {de_pair.push_back(key[index_2-1]);} } } else { int new_index_1 = row_1*5 + col_2; int new_index_2 = row_2*5 + col_1; de_pair.push_back(key[new_index_1]); de_pair.push_back(key[new_index_2]); } return de_pair; } string encode(const string &plaintxt, const string &key){ /* takes in plain txt and uses prepare_plaintext function to make it an even and compatible form of plain text, and uses encode_pair function to sort by each two-character then print out the encoded string */ string encoded; string new_plaintext = prepare_plaintext(plaintxt); for (string::size_type i=0; i< new_plaintext.size(); i+=2){ encoded += encode_pair(new_plaintext.substr(i,2),key); } return encoded; } string decode(const string &encodedtxt, const string &key){ /* opposite to encode, takes in already encoded text string, and then uses decode_pair function to get back to original two-character, then puts it back together to decdoed(original) string */ string decoded; for (string::size_type i = 0; i< encodedtxt.size(); i+=2){ decoded += decode_pair(encodedtxt.substr(i,2),key); } return decoded; }
[ "himsangseung@hotmail.com" ]
himsangseung@hotmail.com
bee2a2f6f070865825ed74ce5c5bf9ccd203926b
b05ea37f8f51d377aee08f73485e06c4ebe941fe
/include/wee/core/tee.hpp
b1505be53d73714fd23ed23d42cbdc12dc07313f
[ "MIT" ]
permissive
emdagh/wee
41314e23ba1d40bf4e362f505fab218d997c1349
b224740c66231e8ce5e82a79451f7ad1f2f87646
refs/heads/master
2023-05-02T13:13:16.427737
2023-04-25T11:22:37
2023-04-25T11:22:37
144,500,976
1
1
MIT
2021-11-11T07:28:49
2018-08-12T21:09:33
C++
UTF-8
C++
false
false
1,236
hpp
#pragma once template <typename T, typename Traits = std::char_traits<T> > class basic_teebuf : public std::basic_streambuf<T, Traits> { typedef typename Traits::int_type int_type; typedef std::basic_streambuf<T, Traits> streambuf_type; streambuf_type* _s0; streambuf_type* _s1; protected: virtual int overflow(int_type c) { if(c == Traits::eof()) { return !Traits::eof(); } int r1 = _s0->sputc(c); int r2 = _s1->sputc(c); return r1 == Traits::eof() || r2 == Traits::eof(); } virtual int sync() { int r1 = _s0->pubsync(); int r2 = _s1->pubsync(); return r1 == 0 && r2 == 0 ? 0 : -1; } public: basic_teebuf(streambuf_type* s0, streambuf_type* s1) : _s0(s0) , _s1(s1) { } }; template <typename T, typename Traits = std::char_traits<T> > class basic_teestream : public std::basic_ostream<T, Traits> { typedef std::basic_ostream<T, Traits> stream_type; typedef basic_teebuf<T, Traits> streambuf_type; streambuf_type _buf; public: basic_teestream(stream_type& s0, stream_type& s1) : stream_type(&_buf) , _buf(s0.rdbuf(), s1.rdbuf()) { } };
[ "emiel.van.dam@hetconsultancyhuis.nl" ]
emiel.van.dam@hetconsultancyhuis.nl
925259bf47bf48eafec27c4d6e0dcb87b3886ceb
10d62a9843ff91d8df37de50c8d0ba3a4d636711
/cXmlParser.cpp
481cd29ea562714b7040741153c9a46283dfb6e7
[]
no_license
JimyRFP/XMLParseCPP
4fd9e9364022e9f0ed655f109773c64a77fe4b8d
f52a5662adbf2daf53ca15fac5904bd4017d7706
refs/heads/main
2023-02-23T07:42:07.511869
2021-01-26T18:50:20
2021-01-26T18:50:20
325,151,980
0
0
null
null
null
null
UTF-8
C++
false
false
11,422
cpp
#ifndef CXMLPARSER_CPP #define CXMLPARSER_CPP #include "cXmlParser.h" void cXmlParser::zeroMemory(xml_StructInfo* structToZero){ structToZero->attributes=NULL; structToZero->attributesValue=NULL; structToZero->father=NULL; structToZero->name=NULL; structToZero->nAttributes=0; structToZero->next=NULL; structToZero->prev=NULL; structToZero->value=NULL; structToZero->isclose=false; }; xml_StructInfo* cXmlParser::parser(const char* dataToParser){ int numberOfTags=0; int indData=0; char *tagName; xml_StructInfo* returnStructRef,*currentStructRef,*prevStructRef=NULL; int strLen=m_StrF.getStringLen((const mystr)dataToParser); returnStructRef=createXmlStruct(); currentStructRef=returnStructRef; while(dataToParser[indData]!=STRING_END){ while(dataToParser[indData]!=CXMLPARSER_OPENTAG_INIT && dataToParser[indData]!=STRING_END)indData++; if(dataToParser[indData]==STRING_END)break; if(m_StrF.strCompare((mystr)&(dataToParser[indData]),(mystr)CXMLPARSER_CLOSETAG_STRING,2)){ indData+=CXMLPARSER_CLOSETAG_LEN; setTagEnd(currentStructRef,dataToParser,&indData); continue; } tagName=getTagName(dataToParser,&indData); if(tagName==NULL){ #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"Null TagName",""); #endif continue; } if(numberOfTags>0){ prevStructRef=currentStructRef; currentStructRef->next=createXmlStruct(); if(currentStructRef->next==NULL){ #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"Alloc Erro",""); #endif freeMemory(&returnStructRef); return NULL; } currentStructRef=currentStructRef->next; currentStructRef->prev=prevStructRef; } currentStructRef->name=tagName; currentStructRef->nAttributes=getAttsNameAndValue(dataToParser,&indData,&(currentStructRef->attributes),&(currentStructRef->attributesValue)); currentStructRef->value=getTagValue(dataToParser,&indData); numberOfTags++; } if(numberOfTags==0){ freeMemory(&returnStructRef); return NULL; } return returnStructRef; }; char* cXmlParser::getTagName(const char* data,int*dataInd){ mystr tagName=NULL; (*dataInd)+=getFirstInvalidChars((const mystr)&data[*dataInd],(const mystr)CXMLPARSER_TAGNAME_FIRST_INVALIDCHARS); (*dataInd)+=getStrUntilStopChar(&tagName,(const mystr)&data[*dataInd],(const mystr)CXMLPARSER_TAGNAME_STOPCHARS); #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"TagName",tagName); #endif return (char*)tagName; } int cXmlParser::getAttsNameAndValue(const char*data,int*dataInd,char***retAttName,char***retAttValue){ int numberOfAttributes=0; mystr tempStr=NULL; while(data[*dataInd]!=STRING_END && data[*dataInd]!=CXMLPARSER_ENDTAG){ //GETPARAM NAME (*dataInd)+=getStrUntilStopChar(&tempStr,(const mystr)&(data[*dataInd]),(const mystr)CXMLPARSER_TAGPARAM_NAME_STOPCHARS); (*dataInd)+=getFirstInvalidChars((const mystr)&(data[*dataInd]),(const mystr)CXMLPARSER_TAGPARAM_NAME_FIRST_INVALIDCHARS); if(tempStr==NULL)continue; numberOfAttributes++; if(!allocAttNameAndValueMemory(retAttName,retAttValue,numberOfAttributes))return 0; #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"TagAttName",tempStr); #endif (*retAttName)[numberOfAttributes-1]=tempStr; (*retAttValue)[numberOfAttributes-1]=NULL; if(data[*dataInd]==CXMLPARSER_ENDTAG)return numberOfAttributes; if(data[*dataInd]!='\"')continue; (*dataInd)++; (*dataInd)+=getStrUntilStopChar(&tempStr,(const mystr)&(data[*dataInd]),(const mystr)CXMLPARSER_TAGPARAM_VALUE_STOPCHARS); (*dataInd)+=getFirstInvalidChars((const mystr)&(data[*dataInd]),(const mystr)CXMLPARSER_TAGPARAM_VALUE_FIRST_INVALIDCHARS); #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"TagAttValue",tempStr); #endif if(tempStr!=NULL){ (*retAttValue)[numberOfAttributes-1]=tempStr; } } return numberOfAttributes; } char *cXmlParser::getTagValue(const char *data,int *dataInd){ mystr tagValueStr=NULL; (*dataInd)+=getFirstInvalidChars((const mystr)&data[*dataInd],(const mystr)CXMLPARSER_TAGVALUE_FIRST_INVALIDCHARS); (*dataInd)+=getStrUntilStopChar(&tagValueStr,(const mystr)&(data[*dataInd]),(const mystr)CXMLPARSER_TAGVALUE_STOPCHARS); #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"TagValue",tagValueStr); #endif return tagValueStr; } void cXmlParser::setTagEnd(xml_StructInfo*strRet,const char *data,int*dataInd){ mystr tagEndStr=NULL; xml_StructInfo*infoRef,*fatherRef; (*dataInd)+=getStrUntilStopChar(&tagEndStr,(const mystr)&(data[*dataInd]),(const mystr)CXMLPARSER_TAGEND_STOPCHARS); if(tagEndStr==NULL)return; infoRef=strRet; while(infoRef!=NULL){ if(m_StrF.strCompare(infoRef->name,tagEndStr) && !infoRef->isclose){ infoRef->isclose=true; #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"Closed",infoRef->name); #endif fatherRef=infoRef->prev; while(fatherRef!=NULL){ if(!fatherRef->isclose){ infoRef->father=fatherRef; #ifdef CXMLPARSER_DEBUG sendDebugMessage(__func__,"FatherName",fatherRef->name); #endif break; } fatherRef=fatherRef->prev; } break; } infoRef=infoRef->prev; } m_StrF.freeStr(&tagEndStr); } void cXmlParser::Print(const xml_StructInfo*info){ if(info==NULL)return; xml_StructInfo *base=(xml_StructInfo *)info; while(1){ printf("TagName: %s\n",base->name); printf("nAttributes %d\n",base->nAttributes); for(int i=0;i<base->nAttributes;i++){ printf("%s=\"%s\" ",base->attributes[i],base->attributesValue[i]); } if(base->nAttributes>0)printf("\n"); if(base->value!=NULL) printf("TagValue: %s\n",base->value); printf("TagIsClose: %d\n",base->isclose); if(base->father!=NULL){ printf("FatherTagName %s\n",base->father->name); } printf("\n\n\n\n"); if(base->next==NULL)break; base=base->next; } } xml_StructInfo* cXmlParser::getRefByAttributeName(const xml_StructInfo*structRef,const char *attName){ xml_StructInfo*currentReadRef,*returnRef=NULL,*addStructRef=NULL; currentReadRef=(xml_StructInfo*)structRef; bool hasAttName; bool refIsSet=false; while(currentReadRef!=NULL){ hasAttName=false; for(int i=0;i<currentReadRef->nAttributes;i++){ if(m_StrF.strCompare((mystr)attName,(mystr)currentReadRef->attributes[i])){ hasAttName=true; break; } } if(hasAttName){ if(!refIsSet){ if(!copyStr(currentReadRef,&returnRef))return NULL; returnRef->prev=NULL; refIsSet=true; addStructRef=returnRef; }else{ if(!copyStr(currentReadRef,&addStructRef->next)){ freeMemory(&returnRef); return NULL; } addStructRef=addStructRef->next; } } currentReadRef=currentReadRef->next; } if(addStructRef!=NULL)addStructRef->next=NULL; return returnRef; } xml_StructInfo* cXmlParser::getRefByTagName(const xml_StructInfo *base,const char *tagName){ if(tagName==NULL)return NULL; xml_StructInfo*returnRef=NULL; xml_StructInfo*addStructRef=NULL; xml_StructInfo*currentReadRef=(xml_StructInfo*)base; while(currentReadRef!=NULL){ if(m_StrF.strCompare(currentReadRef->name,(mystr)tagName)){ if(returnRef==NULL){ copyStr(currentReadRef,&returnRef); if(returnRef==NULL)return NULL; returnRef->next=NULL; addStructRef=returnRef; }else{ copyStr(currentReadRef,&addStructRef->next); if(addStructRef->next==NULL){ freeMemory(&returnRef); return NULL; } addStructRef=returnRef->next; addStructRef->next=NULL; } } currentReadRef=currentReadRef->next; } return returnRef; } bool cXmlParser::copyStr(const xml_StructInfo*source,xml_StructInfo**destination){ if(source==NULL)return false; *destination=createXmlStruct(); if(*destination==NULL)return false; (*destination)->attributes=m_StrF.copyStrArray(source->attributes,source->nAttributes); (*destination)->attributesValue=m_StrF.copyStrArray(source->attributesValue,source->nAttributes); (*destination)->father=source->father; (*destination)->isclose=source->isclose; (*destination)->name=m_StrF.copyStr(source->name); (*destination)->nAttributes=source->nAttributes; (*destination)->next=source->next; (*destination)->prev=source->prev; (*destination)->value=m_StrF.copyStr(source->value); return true; } void cXmlParser::freeMemory(xml_StructInfo**structToFree){ xml_StructInfo *nextRefToFree,*currentRefToFree=*structToFree; if(currentRefToFree==NULL)return; while(currentRefToFree!=NULL){ m_StrF.freeStrArray(&currentRefToFree->attributes,currentRefToFree->nAttributes); m_StrF.freeStrArray(&currentRefToFree->attributesValue,currentRefToFree->nAttributes); m_StrF.freeStr(&currentRefToFree->value); m_StrF.freeStr(&currentRefToFree->name); nextRefToFree=currentRefToFree->next; free(currentRefToFree); currentRefToFree=nextRefToFree; } *structToFree=NULL; } xml_StructInfo* cXmlParser::createXmlStruct(){ xml_StructInfo*structRef=(xml_StructInfo*)malloc(sizeof(xml_StructInfo)); if(structRef==NULL)return NULL; zeroMemory(structRef); return structRef; } void cXmlParser::sendDebugMessage(const char*fName,const char*message1=NULL,const char*message2=NULL){ #ifndef CXMLPARSER_DEBUG return; #endif printf("Function Name: %s Message1: %s Message2: %s\n",fName,message1,message2); } inline int cXmlParser::getStrUntilStopChar(mystr*returnStr,const mystr source,const mystr stopCharList){ *returnStr=NULL; int sourceInd=getStrIndUntilStopChar(source,stopCharList); if(sourceInd==0)return sourceInd; m_StrF.strAdd(returnStr,source,sourceInd); *returnStr=m_StrF.trimFree(*returnStr); if(*returnStr==NULL)return 0; return sourceInd; }; inline int cXmlParser::getStrIndUntilStopChar(const mystr source,const mystr stopCharList){ int sourceInd=0,stopCharListInd=0; bool stopCharFound; while(source[sourceInd]!=STRING_END){ stopCharListInd=0; stopCharFound=false; while(stopCharList[stopCharListInd]!=STRING_END){ if(stopCharList[stopCharListInd]==source[sourceInd]){ stopCharFound=true; break; } stopCharListInd++; } if(stopCharFound)break; sourceInd++; } return sourceInd; } bool cXmlParser::allocAttNameAndValueMemory(mystr**retAttName,mystr**retAttValue,const int numberOfAttributes){ *retAttName=(mystr*)realloc(*retAttName,numberOfAttributes*sizeof(mystr)); *retAttValue=(mystr*)realloc(*retAttValue,numberOfAttributes*sizeof(mystr)); if(*retAttName==NULL || *retAttValue==NULL){ m_StrF.freeStrArray(retAttName,numberOfAttributes); m_StrF.freeStrArray(retAttValue,numberOfAttributes); return false; } (*retAttName)[numberOfAttributes-1]=NULL; (*retAttValue)[numberOfAttributes-1]=NULL; return true; } inline int cXmlParser::getFirstInvalidChars(const mystr source,const mystr stopCharList){ int sourceInd=0,stopCharListInd=0; bool invalidCharFound=false; while(source[sourceInd]!=STRING_END){ invalidCharFound=false; stopCharListInd=0; while(stopCharList[stopCharListInd]!=STRING_END){ if(stopCharList[stopCharListInd]==source[sourceInd]){ invalidCharFound=true; } stopCharListInd++; } if(!invalidCharFound)break; sourceInd++; } return sourceInd; } #endif
[ "rafaelflorianipinto@gmail.com" ]
rafaelflorianipinto@gmail.com
9385ffb05771638b30e211d81f5f295cec08f6a6
f05bde6d5bdee3e9a07e34af1ce18259919dd9bd
/algorithms/kernel/low_order_moments/low_order_moments_csr_sum_online_fpt_dispatcher.cpp
0626b30e8471568ad0eb00d527a1fb8ad063ee29
[ "Intel", "Apache-2.0" ]
permissive
HFTrader/daal
f827c83b75cf5884ecfb6249a664ce6f091bfc57
b18624d2202a29548008711ec2abc93d017bd605
refs/heads/daal_2017_beta
2020-12-28T19:08:39.038346
2016-04-15T17:02:24
2016-04-15T17:02:24
56,404,044
0
1
null
2016-04-16T20:26:14
2016-04-16T20:26:14
null
UTF-8
C++
false
false
1,130
cpp
/* file: low_order_moments_csr_sum_online_fpt_dispatcher.cpp */ /******************************************************************************* * Copyright 2014-2016 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Instantiation of online low order moments algorithm container. //-- */ #include "low_order_moments_container.h" namespace daal { namespace algorithms { namespace interface1 { __DAAL_INSTANTIATE_DISPATCH_CONATINER(low_order_moments::OnlineContainer, online, DAAL_FPTYPE, low_order_moments::sumCSR) } } }
[ "vasily.rubtsov@intel.com" ]
vasily.rubtsov@intel.com
add7c52b90657d83cd3f9a99ae0e4f382f0cd746
2fcee87709417717620d2ca4131f96e29c0bc320
/Codeforces/codeforcs_304_A.cpp
d4f96d6ca408959c1fc7ca965726baf31d1a8f17
[]
no_license
Jaminur-Rashid/Problem-Solving
7b502b03c5eea180282adcaad1b74ab526c92f12
c651c9e810dba6a8f4b1ece6a3c27554d4a49ac0
refs/heads/master
2023-07-27T15:22:14.744541
2021-09-09T12:13:13
2021-09-09T12:13:13
404,700,331
1
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
#include<bits/stdc++.h> #include<cstdio> using namespace std; int main(){ long long int k,n,m,sum,borrow; int i; scanf("%lld %lld %lld",&k,&n,&m); sum=0; for( i=1;i<=m;i++){ sum=sum+k*i; } borrow=sum-n; if(sum<=n){ printf("0\n"); } else{ printf("%lld\n",borrow); } return 0; }
[ "jaminurrashid21@gmail.com" ]
jaminurrashid21@gmail.com
1290dbfd7821b1ac20259d5ec056d22c49d20163
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/07/71c2925db509c4/main.cpp
bf3163ffead991abcdf24832e21b2876bee66c95
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
2,672
cpp
#include <iostream> #include <vector> #include <deque> #include <type_traits> namespace detail { template<class> struct sfinae_true : std::true_type{}; template<class T, class A0> static auto test_reserve(int) ->sfinae_true<decltype(std::declval<T>().reserve(std::declval<A0>()))>; template<class, class A0> static auto test_reserve(long)->std::false_type; template<class T, class A0> static auto test_resize(int) ->sfinae_true<decltype(std::declval<T>().resize(std::declval<A0>()))>; template<class, class A0> static auto test_resize(long)->std::false_type; } //check if class T have reserve(Arg) function template<class T, class Arg> struct HasReserve : decltype(detail::test_reserve<T, Arg>(0)){}; //check if class T have resize(Arg) function template<class T, class Arg> struct HasResize : decltype(detail::test_resize<T, Arg>(0)){}; //enable if resize function exists and there is no reserve function template<class T1, class T2> typename std::enable_if<HasResize< T1, typename T1::size_type>::value && (!HasReserve< T1, typename T1::value_type>::value), void>::type inline reserveOrResize(T1& dst, T2&& src, typename T2::size_type newSize){ static_assert(std::is_lvalue_reference<T1&>::value, "You must pass lvalue_refrence as first parameter"); static_assert(std::is_rvalue_reference<T2&&>::value, "You must pass rvalue_refrence as second parameter"); int loc = dst.size() + 1; dst.resize(newSize); std::cout << "Resizing\n"; for (auto&& elem : src){ dst[loc++] = std::move(elem); } } //enable if reserve function exists template<class T1, class T2> typename std::enable_if<HasReserve< T1, typename T1::size_type>::value, void>::type inline reserveOrResize(T1& dst, T2&& src, typename T2::size_type newSize){ static_assert(std::is_lvalue_reference<T1&>::value, "You must pass lvalue_refrence as first parameter"); static_assert(std::is_rvalue_reference<T2&&>::value, "You must pass rvalue_refrence as second parameter"); src.reserve(newSize); std::cout << "Reserving\n"; for (auto&& elem : src){ dst.push_back(std::move(elem)); } } //push_back container T2 at the end of Container T1 //T2 must be rvalue refrence template<class T1, class T2> void push_back(T1& dst, T2&& src){ static_assert(std::is_lvalue_reference<T1&>::value, "You must pass lvalue_refrence as first parameter"); static_assert(std::is_rvalue_reference<T2&&>::value, "You must pass rvalue_refrence as second parameter"); reserveOrResize(dst, std::move(src), src.size()); } struct A{}; int main(){ std::vector<A> vec; push_back(vec, std::vector<A>(10)); }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
9cd7404325c75813ccaa3862a8219bfcd7791a60
031009bf00a8d7cd564e0f768ff3649907bd5b65
/TorrentBuild_CPPApp.cpp
2a3edb79ce5a5898c1c7b18e03a5913e28b1b597
[]
no_license
usertex/autov
237ab3b655be2dffcb7292cd212fe2b6d95907a7
b470a96072484afe73ab0ae6ab7096970e34d973
refs/heads/master
2020-04-19T02:45:34.548955
2006-07-03T01:37:24
2006-07-03T01:37:24
67,372,523
0
0
null
null
null
null
UTF-8
C++
false
false
676
cpp
//--------------------------------------------------------------------------- // // Name: TorrentBuild_CPPApp.cpp // Author: Harold Feit // Created: 5/19/2006 11:09:52 AM // Description: // //--------------------------------------------------------------------------- #include "TorrentBuild_CPPFunctions.h" #include "TorrentBuild_CPPApp.h" #include "TorrentBuild_CPPDlg.h" IMPLEMENT_APP(TorrentBuild_CPPDlgApp) bool TorrentBuild_CPPDlgApp::OnInit() { TorrentBuild_CPPDlg* dialog = new TorrentBuild_CPPDlg(NULL); SetTopWindow(dialog); dialog->Show(true); return true; } int TorrentBuild_CPPDlgApp::OnExit() { return 0; }
[ "DreadWingKnight@users.noreply.github.com" ]
DreadWingKnight@users.noreply.github.com
ecd3969133227a7f1f46f4aef653bf1a7fa745f5
799f7938856a320423625c6a6a3881eacdd0e039
/mlir/include/mlir/Dialect/PDL/IR/PDLTypes.h
a9028f3d597208abb2a99147bbe67ace2923aae0
[ "LLVM-exception", "Apache-2.0" ]
permissive
shabalind/llvm-project
3b90d1d8f140efe1b4f32390f68218c02c95d474
d06e94031bcdfa43512bf7b0cdfd4b4bad3ca4e1
refs/heads/main
2022-10-18T04:13:17.818838
2021-02-04T13:06:43
2021-02-04T14:23:33
237,532,515
0
0
Apache-2.0
2020-01-31T23:17:24
2020-01-31T23:17:23
null
UTF-8
C++
false
false
946
h
//===- PDLTypes.h - Pattern Descriptor Language Types -----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the types for the Pattern Descriptor Language dialect. // //===----------------------------------------------------------------------===// #ifndef MLIR_DIALECT_PDL_IR_PDLTYPES_H_ #define MLIR_DIALECT_PDL_IR_PDLTYPES_H_ #include "mlir/IR/Types.h" //===----------------------------------------------------------------------===// // PDL Dialect Types //===----------------------------------------------------------------------===// #define GET_TYPEDEF_CLASSES #include "mlir/Dialect/PDL/IR/PDLOpsTypes.h.inc" #endif // MLIR_DIALECT_PDL_IR_PDLTYPES_H_
[ "riddleriver@gmail.com" ]
riddleriver@gmail.com
64fc762f8510fbed031701fed23a7b4bafcbc161
cc8ba0ab3dbc3fb63b6279418b51eae4c76e1b63
/arm_o/djournaljobavp.cpp
5a46ee3ff30e2eced9eb6601a7bc99e363cb492f
[]
no_license
levdikandrey/DataCollector
2c08e34277787fee53d407b8b401f14e58a974da
7a79029c7936c26c2d2a4d1396a0d996de9ee2ea
refs/heads/master
2021-06-26T12:37:02.206691
2021-06-10T11:03:54
2021-06-10T11:03:54
229,206,596
2
0
null
null
null
null
UTF-8
C++
false
false
8,112
cpp
#include "djournaljobavp.h" #include "ui_d_journaljobavp.h" #include "mainwindow.h" #include <QSqlDatabase> #include <QSqlError> #include <QTableWidget> #include <QDebug> #include <QMessageBox> extern QSqlDatabase db; //========================================================= DJournalJobAVP::DJournalJobAVP(QWidget *parent) : QDialog(parent), ui(new Ui::DJournalJobAVP) { ui->setupUi(this); query = new QSqlQuery(db); initDialog(); reinterpret_cast<MainWindow*>(parent)->initComboBoxUser(ui->comboBoxUser); initTableJournalSession(); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); } //========================================================= DJournalJobAVP::~DJournalJobAVP() { delete ui; } //========================================================= void DJournalJobAVP::initDialog() { ui->tableWidget->horizontalHeader()->resizeSection(0, 200);//Date ui->tableWidget->horizontalHeader()->resizeSection(1, 250);//FIO ui->tableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);//Session ui->tableWidget->horizontalHeader()->resizeSection(3, 150);//Category } //========================================================= void DJournalJobAVP::initTableJournalSession() { QString sql=""; try { ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(0); sql = "SELECT jj.\"DateEvent\",u.\"FIO\",jj.\"Info\",jj.\"Сategory\",jj.\"NameAVP\" FROM \"JournalJobAVP\" jj INNER JOIN \"User\" u ON jj.\"ID_User\" = u.\"ID\";"; if(query->exec(sql)) { int row=0; while(query->next()) { ui->tableWidget->setRowCount(row+1); QTableWidgetItem *newItem = new QTableWidgetItem(); QIcon icon; icon.addFile(QString::fromUtf8(":/icons/icons/date2.png"), QSize(), QIcon::Normal, QIcon::Off); newItem->setIcon(icon); newItem->setText(query->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss")); ui->tableWidget->setItem(row,0, newItem); newItem->setFlags(newItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *newItem1 = new QTableWidgetItem(); newItem1->setFlags(newItem1->flags() ^ Qt::ItemIsEditable); QIcon icon1; icon1.addFile(QString::fromUtf8(":/icons/icons/user.png"), QSize(), QIcon::Normal, QIcon::Off); newItem1->setIcon(icon1); newItem1->setText(query->value(1).toString()); ui->tableWidget->setItem(row,1, newItem1); QTableWidgetItem *newItem3 = new QTableWidgetItem(); newItem3->setText(query->value(2).toString()+": "+query->value(4).toString()); ui->tableWidget->setItem(row,2, newItem3); QTableWidgetItem *newItem4 = new QTableWidgetItem(); newItem4->setText(query->value(3).toString()); ui->tableWidget->setItem(row,3, newItem4); row++; } } else { qDebug()<<query->lastError().text(); } } catch(std::exception &e) { qDebug()<<e.what(); } } //========================================================= void DJournalJobAVP::slotReview() { QString sql=""; bool filterCheck = false; try { ui->tableWidget->setSortingEnabled(false); ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(0); // sql = "SELECT ss.\"DateEvent\",u.\"FIO\",ss.\"Info\",ss.\"Сategory\",ss.\"NameAVP\" FROM \"JournalJobAVP\" ss INNER JOIN \"User\" u ON ss.\"ID_User\" = u.\"ID\";"; sql = "SELECT ss.\"DateEvent\",u.\"FIO\",ss.\"Info\",ss.\"Сategory\",ss.\"NameAVP\" FROM \"JournalJobAVP\" ss INNER JOIN \"User\" u ON ss.\"ID_User\" = u.\"ID\""; if(ui->groupBoxUser->isChecked()) { sql +=" WHERE u.\"FIO\" = \'";sql += ui->comboBoxUser->currentText(); sql += "\'"; filterCheck = true; } if(ui->groupBoxDate->isChecked()) { if(!filterCheck) { sql +=" WHERE (ss.\"DateEvent\" >='"; sql += ui->dateEditDateBegin->date().toString("yyyy-MM-dd"); sql += "\'::date AND ss.\"DateEvent\" <=\'";sql += ui->dateEditDateEnd->date().toString("yyyy-MM-dd"); sql += "\'::date + \'1 day\'::interval)"; } else { sql +=" AND (ss.\"DateEvent\" >='"; sql += ui->dateEditDateBegin->date().toString("yyyy-MM-dd"); sql += "\'::date AND ss.\"DateEvent\" <=\'";sql += ui->dateEditDateEnd->date().toString("yyyy-MM-dd"); sql += "\'::date + \'1 day\'::interval)"; } filterCheck = true; } sql += " ORDER BY ss.\"ID\";"; qDebug()<<"sql = "<<sql; if(query->exec(sql)) { int row = 0; while(query->next()) { ui->tableWidget->setRowCount(row+1); QTableWidgetItem *newItem = new QTableWidgetItem(); QIcon icon; icon.addFile(QString::fromUtf8(":/icons/icons/date2.png"), QSize(), QIcon::Normal, QIcon::Off); newItem->setIcon(icon); newItem->setText(query->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss")); ui->tableWidget->setItem(row,0, newItem); newItem->setFlags(newItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *newItem1 = new QTableWidgetItem(); newItem1->setFlags(newItem1->flags() ^ Qt::ItemIsEditable); QIcon icon1; icon1.addFile(QString::fromUtf8(":/icons/icons/user.png"), QSize(), QIcon::Normal, QIcon::Off); newItem1->setIcon(icon1); newItem1->setText(query->value(1).toString()); ui->tableWidget->setItem(row,1, newItem1); QTableWidgetItem *newItem3 = new QTableWidgetItem(); newItem3->setText(query->value(2).toString()+": "+query->value(4).toString()); ui->tableWidget->setItem(row,2, newItem3); QTableWidgetItem *newItem4 = new QTableWidgetItem(); newItem4->setText(query->value(3).toString()); ui->tableWidget->setItem(row,3, newItem4); // QTableWidgetItem *newItem = new QTableWidgetItem(); // QIcon icon; // icon.addFile(QString::fromUtf8(":/icons/icons/date2.png"), QSize(), QIcon::Normal, QIcon::Off); // newItem->setIcon(icon); // newItem->setText(query->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss")); // ui->tableWidget->setItem(row,0, newItem); // newItem->setFlags(newItem->flags() ^ Qt::ItemIsEditable); // QTableWidgetItem *newItem1 = new QTableWidgetItem(); // newItem1->setFlags(newItem1->flags() ^ Qt::ItemIsEditable); // QIcon icon1; // icon1.addFile(QString::fromUtf8(":/icons/icons/user.png"), QSize(), QIcon::Normal, QIcon::Off); // newItem1->setIcon(icon1); // newItem1->setText(query->value(1).toString()); // ui->tableWidget->setItem(row,1, newItem1); // QTableWidgetItem *newItem3 = new QTableWidgetItem(); // newItem3->setText(query->value(2).toString()); // ui->tableWidget->setItem(row,2, newItem3); // QTableWidgetItem *newItem4 = new QTableWidgetItem(); // newItem3->setText(query->value(3).toString()); // ui->tableWidget->setItem(row,3, newItem4); row++; } } else { qDebug()<<query->lastError().text(); } } catch(std::exception &e) { qDebug()<<e.what(); } } //========================================================= void DJournalJobAVP::slotExit() { accept(); }
[ "a.levdik@grfc.ru" ]
a.levdik@grfc.ru
eeb090df6436d903914faed5195003bd9805a9b8
8b682b91b3d06afc403de23bf2c93c9ceacbeab7
/pol-core/clib/dirfunc.h
6cdac86977cbae1ad7675c87d14548bde1853a8f
[]
no_license
jagarop/POL_099b
1803f3e369c2c1500f601f736059fe2908da3711
6a5df8893b6f38ff57a42412420813f3a3b83227
refs/heads/master
2021-07-16T16:33:19.905934
2015-01-08T01:44:03
2015-01-08T01:44:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,510
h
#ifndef __DIRFUNC_H #define __DIRFUNC_H #ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdlib.h> #define MAXDRIVE _MAX_DRIVE #define MAXDIR _MAX_DIR #define MAXFILE _MAX_FNAME #define MAXPATH _MAX_PATH #define MAXEXT _MAX_EXT #else #ifndef __DIR_H #include <dir.h> #endif #endif namespace Pol { namespace Clib { #define MAXFULLDIR (MAXDRIVE+MAXDIR-1) #define MAXFNAME (MAXFILE+MAXEXT-1) typedef char Directory[MAXFULLDIR]; typedef char File1[MAXFILE]; typedef char FFile[MAXFNAME]; typedef char Pathname[MAXPATH]; extern char temp_path[MAXPATH]; extern char temp_drive[MAXDRIVE]; extern char temp_dir[MAXDIR]; extern char temp_fname[MAXFILE]; extern char temp_ext[MAXEXT]; int fullsplit( const char *path ); char *fullmerge( char *path ); char *mergeFnExt( char *path ); char *nodefile( const char *directory, const char *filename, int node ); char *buildfn( const char *directory, const char *filename ); char *buildfnext( const char *dir, const char *file, const char *ext ); void normalize_dir( char *dir ); int strip_one( char *direc ); enum { SRC_NO_EXIST = 1, DST_ALREADY_EXIST, SRC_OPEN_ERROR, DST_OPEN_ERROR, WRITE_ERROR }; extern int mydir_errno; int copyFile( const char *src, const char *dst ); int copyFileNoRep( const char *src, const char *dst ); int moveFile( const char *src, const char *dst ); int moveFileNoRep( const char *src, const char *dst ); int chddir( const char *directory ); } } #endif
[ "necr0potenc3@users.noreply.github.com" ]
necr0potenc3@users.noreply.github.com
968049e25a9f5f91e97bae12e952b808f32d03a4
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/vpc/include/tencentcloud/vpc/v20170312/model/Route.h
1c4e09b248945601713f53ee7da24cba8a13a54e
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
19,260
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #ifndef TENCENTCLOUD_VPC_V20170312_MODEL_ROUTE_H_ #define TENCENTCLOUD_VPC_V20170312_MODEL_ROUTE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Vpc { namespace V20170312 { namespace Model { /** * 路由策略对象 */ class Route : public AbstractModel { public: Route(); ~Route() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取目的网段,取值不能在私有网络网段内,例如:112.20.51.0/24。 * @return DestinationCidrBlock 目的网段,取值不能在私有网络网段内,例如:112.20.51.0/24。 * */ std::string GetDestinationCidrBlock() const; /** * 设置目的网段,取值不能在私有网络网段内,例如:112.20.51.0/24。 * @param _destinationCidrBlock 目的网段,取值不能在私有网络网段内,例如:112.20.51.0/24。 * */ void SetDestinationCidrBlock(const std::string& _destinationCidrBlock); /** * 判断参数 DestinationCidrBlock 是否已赋值 * @return DestinationCidrBlock 是否已赋值 * */ bool DestinationCidrBlockHasBeenSet() const; /** * 获取下一跳类型,目前我们支持的类型有: CVM:公网网关类型的云服务器; VPN:VPN网关; DIRECTCONNECT:专线网关; PEERCONNECTION:对等连接; HAVIP:高可用虚拟IP; NAT:NAT网关; NORMAL_CVM:普通云服务器; EIP:云服务器的公网IP; LOCAL_GATEWAY:本地网关。 * @return GatewayType 下一跳类型,目前我们支持的类型有: CVM:公网网关类型的云服务器; VPN:VPN网关; DIRECTCONNECT:专线网关; PEERCONNECTION:对等连接; HAVIP:高可用虚拟IP; NAT:NAT网关; NORMAL_CVM:普通云服务器; EIP:云服务器的公网IP; LOCAL_GATEWAY:本地网关。 * */ std::string GetGatewayType() const; /** * 设置下一跳类型,目前我们支持的类型有: CVM:公网网关类型的云服务器; VPN:VPN网关; DIRECTCONNECT:专线网关; PEERCONNECTION:对等连接; HAVIP:高可用虚拟IP; NAT:NAT网关; NORMAL_CVM:普通云服务器; EIP:云服务器的公网IP; LOCAL_GATEWAY:本地网关。 * @param _gatewayType 下一跳类型,目前我们支持的类型有: CVM:公网网关类型的云服务器; VPN:VPN网关; DIRECTCONNECT:专线网关; PEERCONNECTION:对等连接; HAVIP:高可用虚拟IP; NAT:NAT网关; NORMAL_CVM:普通云服务器; EIP:云服务器的公网IP; LOCAL_GATEWAY:本地网关。 * */ void SetGatewayType(const std::string& _gatewayType); /** * 判断参数 GatewayType 是否已赋值 * @return GatewayType 是否已赋值 * */ bool GatewayTypeHasBeenSet() const; /** * 获取下一跳地址,这里只需要指定不同下一跳类型的网关ID,系统会自动匹配到下一跳地址。 特殊说明:GatewayType为NORMAL_CVM时,GatewayId填写实例的内网IP。 * @return GatewayId 下一跳地址,这里只需要指定不同下一跳类型的网关ID,系统会自动匹配到下一跳地址。 特殊说明:GatewayType为NORMAL_CVM时,GatewayId填写实例的内网IP。 * */ std::string GetGatewayId() const; /** * 设置下一跳地址,这里只需要指定不同下一跳类型的网关ID,系统会自动匹配到下一跳地址。 特殊说明:GatewayType为NORMAL_CVM时,GatewayId填写实例的内网IP。 * @param _gatewayId 下一跳地址,这里只需要指定不同下一跳类型的网关ID,系统会自动匹配到下一跳地址。 特殊说明:GatewayType为NORMAL_CVM时,GatewayId填写实例的内网IP。 * */ void SetGatewayId(const std::string& _gatewayId); /** * 判断参数 GatewayId 是否已赋值 * @return GatewayId 是否已赋值 * */ bool GatewayIdHasBeenSet() const; /** * 获取路由策略ID。IPv4路由策略ID是有意义的值,IPv6路由策略是无意义的值0。后续建议完全使用字符串唯一ID `RouteItemId`操作路由策略。 该字段在删除时必填,其他字段无需填写。 * @return RouteId 路由策略ID。IPv4路由策略ID是有意义的值,IPv6路由策略是无意义的值0。后续建议完全使用字符串唯一ID `RouteItemId`操作路由策略。 该字段在删除时必填,其他字段无需填写。 * */ uint64_t GetRouteId() const; /** * 设置路由策略ID。IPv4路由策略ID是有意义的值,IPv6路由策略是无意义的值0。后续建议完全使用字符串唯一ID `RouteItemId`操作路由策略。 该字段在删除时必填,其他字段无需填写。 * @param _routeId 路由策略ID。IPv4路由策略ID是有意义的值,IPv6路由策略是无意义的值0。后续建议完全使用字符串唯一ID `RouteItemId`操作路由策略。 该字段在删除时必填,其他字段无需填写。 * */ void SetRouteId(const uint64_t& _routeId); /** * 判断参数 RouteId 是否已赋值 * @return RouteId 是否已赋值 * */ bool RouteIdHasBeenSet() const; /** * 获取路由策略描述。 * @return RouteDescription 路由策略描述。 * */ std::string GetRouteDescription() const; /** * 设置路由策略描述。 * @param _routeDescription 路由策略描述。 * */ void SetRouteDescription(const std::string& _routeDescription); /** * 判断参数 RouteDescription 是否已赋值 * @return RouteDescription 是否已赋值 * */ bool RouteDescriptionHasBeenSet() const; /** * 获取是否启用 * @return Enabled 是否启用 * */ bool GetEnabled() const; /** * 设置是否启用 * @param _enabled 是否启用 * */ void SetEnabled(const bool& _enabled); /** * 判断参数 Enabled 是否已赋值 * @return Enabled 是否已赋值 * */ bool EnabledHasBeenSet() const; /** * 获取路由类型,目前我们支持的类型有: USER:用户路由; NETD:网络探测路由,创建网络探测实例时,系统默认下发,不可编辑与删除; CCN:云联网路由,系统默认下发,不可编辑与删除。 用户只能添加和操作 USER 类型的路由。 * @return RouteType 路由类型,目前我们支持的类型有: USER:用户路由; NETD:网络探测路由,创建网络探测实例时,系统默认下发,不可编辑与删除; CCN:云联网路由,系统默认下发,不可编辑与删除。 用户只能添加和操作 USER 类型的路由。 * */ std::string GetRouteType() const; /** * 设置路由类型,目前我们支持的类型有: USER:用户路由; NETD:网络探测路由,创建网络探测实例时,系统默认下发,不可编辑与删除; CCN:云联网路由,系统默认下发,不可编辑与删除。 用户只能添加和操作 USER 类型的路由。 * @param _routeType 路由类型,目前我们支持的类型有: USER:用户路由; NETD:网络探测路由,创建网络探测实例时,系统默认下发,不可编辑与删除; CCN:云联网路由,系统默认下发,不可编辑与删除。 用户只能添加和操作 USER 类型的路由。 * */ void SetRouteType(const std::string& _routeType); /** * 判断参数 RouteType 是否已赋值 * @return RouteType 是否已赋值 * */ bool RouteTypeHasBeenSet() const; /** * 获取路由表实例ID,例如:rtb-azd4dt1c。 * @return RouteTableId 路由表实例ID,例如:rtb-azd4dt1c。 * */ std::string GetRouteTableId() const; /** * 设置路由表实例ID,例如:rtb-azd4dt1c。 * @param _routeTableId 路由表实例ID,例如:rtb-azd4dt1c。 * */ void SetRouteTableId(const std::string& _routeTableId); /** * 判断参数 RouteTableId 是否已赋值 * @return RouteTableId 是否已赋值 * */ bool RouteTableIdHasBeenSet() const; /** * 获取目的IPv6网段,取值不能在私有网络网段内,例如:2402:4e00:1000:810b::/64。 * @return DestinationIpv6CidrBlock 目的IPv6网段,取值不能在私有网络网段内,例如:2402:4e00:1000:810b::/64。 * */ std::string GetDestinationIpv6CidrBlock() const; /** * 设置目的IPv6网段,取值不能在私有网络网段内,例如:2402:4e00:1000:810b::/64。 * @param _destinationIpv6CidrBlock 目的IPv6网段,取值不能在私有网络网段内,例如:2402:4e00:1000:810b::/64。 * */ void SetDestinationIpv6CidrBlock(const std::string& _destinationIpv6CidrBlock); /** * 判断参数 DestinationIpv6CidrBlock 是否已赋值 * @return DestinationIpv6CidrBlock 是否已赋值 * */ bool DestinationIpv6CidrBlockHasBeenSet() const; /** * 获取路由唯一策略ID。 * @return RouteItemId 路由唯一策略ID。 * */ std::string GetRouteItemId() const; /** * 设置路由唯一策略ID。 * @param _routeItemId 路由唯一策略ID。 * */ void SetRouteItemId(const std::string& _routeItemId); /** * 判断参数 RouteItemId 是否已赋值 * @return RouteItemId 是否已赋值 * */ bool RouteItemIdHasBeenSet() const; /** * 获取路由策略是否发布到云联网。 注意:此字段可能返回 null,表示取不到有效值。 * @return PublishedToVbc 路由策略是否发布到云联网。 注意:此字段可能返回 null,表示取不到有效值。 * */ bool GetPublishedToVbc() const; /** * 设置路由策略是否发布到云联网。 注意:此字段可能返回 null,表示取不到有效值。 * @param _publishedToVbc 路由策略是否发布到云联网。 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetPublishedToVbc(const bool& _publishedToVbc); /** * 判断参数 PublishedToVbc 是否已赋值 * @return PublishedToVbc 是否已赋值 * */ bool PublishedToVbcHasBeenSet() const; /** * 获取路由策略创建时间 * @return CreatedTime 路由策略创建时间 * */ std::string GetCreatedTime() const; /** * 设置路由策略创建时间 * @param _createdTime 路由策略创建时间 * */ void SetCreatedTime(const std::string& _createdTime); /** * 判断参数 CreatedTime 是否已赋值 * @return CreatedTime 是否已赋值 * */ bool CreatedTimeHasBeenSet() const; private: /** * 目的网段,取值不能在私有网络网段内,例如:112.20.51.0/24。 */ std::string m_destinationCidrBlock; bool m_destinationCidrBlockHasBeenSet; /** * 下一跳类型,目前我们支持的类型有: CVM:公网网关类型的云服务器; VPN:VPN网关; DIRECTCONNECT:专线网关; PEERCONNECTION:对等连接; HAVIP:高可用虚拟IP; NAT:NAT网关; NORMAL_CVM:普通云服务器; EIP:云服务器的公网IP; LOCAL_GATEWAY:本地网关。 */ std::string m_gatewayType; bool m_gatewayTypeHasBeenSet; /** * 下一跳地址,这里只需要指定不同下一跳类型的网关ID,系统会自动匹配到下一跳地址。 特殊说明:GatewayType为NORMAL_CVM时,GatewayId填写实例的内网IP。 */ std::string m_gatewayId; bool m_gatewayIdHasBeenSet; /** * 路由策略ID。IPv4路由策略ID是有意义的值,IPv6路由策略是无意义的值0。后续建议完全使用字符串唯一ID `RouteItemId`操作路由策略。 该字段在删除时必填,其他字段无需填写。 */ uint64_t m_routeId; bool m_routeIdHasBeenSet; /** * 路由策略描述。 */ std::string m_routeDescription; bool m_routeDescriptionHasBeenSet; /** * 是否启用 */ bool m_enabled; bool m_enabledHasBeenSet; /** * 路由类型,目前我们支持的类型有: USER:用户路由; NETD:网络探测路由,创建网络探测实例时,系统默认下发,不可编辑与删除; CCN:云联网路由,系统默认下发,不可编辑与删除。 用户只能添加和操作 USER 类型的路由。 */ std::string m_routeType; bool m_routeTypeHasBeenSet; /** * 路由表实例ID,例如:rtb-azd4dt1c。 */ std::string m_routeTableId; bool m_routeTableIdHasBeenSet; /** * 目的IPv6网段,取值不能在私有网络网段内,例如:2402:4e00:1000:810b::/64。 */ std::string m_destinationIpv6CidrBlock; bool m_destinationIpv6CidrBlockHasBeenSet; /** * 路由唯一策略ID。 */ std::string m_routeItemId; bool m_routeItemIdHasBeenSet; /** * 路由策略是否发布到云联网。 注意:此字段可能返回 null,表示取不到有效值。 */ bool m_publishedToVbc; bool m_publishedToVbcHasBeenSet; /** * 路由策略创建时间 */ std::string m_createdTime; bool m_createdTimeHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_VPC_V20170312_MODEL_ROUTE_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
fe35aa90acc61eed7e2906408de1fc323602f7f9
6d5767fba2bc0d74ca2d7f5efecef86a07705453
/tests/ordenar_3_numeros_v3.cc
90fc8f08d2cdd84467b663e59d94f89bf610f94d
[]
no_license
pauek/ccjs
d4a4798a062e53506df8f257fdf91ff1bd19b9f2
8f2bb31c72463ef700864f9349ceecc3217a65e3
refs/heads/master
2020-06-02T11:50:59.824402
2011-10-26T21:20:42
2011-10-26T21:20:42
2,606,216
4
2
null
null
null
null
UTF-8
C++
false
false
394
cc
// // Escribe de mayor a menor tres números entrados // por el teclado // #include <iostream> using namespace std; int main() { int a, b, c, tmp; cin >> a >> b >> c; if (a < b) { tmp = a; a = b; b = tmp; } if (a < c) { tmp = a; a = c; c = tmp; } if (b < c) { tmp = b; b = c; c = tmp; } cout << a << ' ' << b << ' ' << c << endl; }
[ "pau.fernandez@upc.edu" ]
pau.fernandez@upc.edu
175621d95a4d86bedc405cdd397855321956e97b
db7148c33aabad259c9e1acafdf6e5c49b627d46
/Tests/Armory/build_test_game/osx-build/Sources/include/kha/audio2/AudioChannel.h
2df801adcee113804dd857cc60da3fd1a52d418a
[]
no_license
templeblock/Animations
18472430af796d32e3f0c9dd2df1058fdb241846
e986fa2249b998889fad78cac6ff3cc70ad196f0
refs/heads/master
2020-04-23T01:23:44.200377
2018-06-07T14:33:43
2018-06-07T14:33:43
null
0
0
null
null
null
null
UTF-8
C++
false
true
2,561
h
// Generated by Haxe 3.4.4 #ifndef INCLUDED_kha_audio2_AudioChannel #define INCLUDED_kha_audio2_AudioChannel #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_kha_audio1_AudioChannel #include <kha/audio1/AudioChannel.h> #endif HX_DECLARE_CLASS2(kha,arrays,Float32ArrayPrivate) HX_DECLARE_CLASS2(kha,audio1,AudioChannel) HX_DECLARE_CLASS2(kha,audio2,AudioChannel) namespace kha{ namespace audio2{ class HXCPP_CLASS_ATTRIBUTES AudioChannel_obj : public hx::Object { public: typedef hx::Object super; typedef AudioChannel_obj OBJ_; AudioChannel_obj(); public: enum { _hx_ClassId = 0x0cffaaed }; void __construct(bool looping); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="kha.audio2.AudioChannel") { return hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return hx::Object::operator new(inSize+extra,true,"kha.audio2.AudioChannel"); } static hx::ObjectPtr< AudioChannel_obj > __new(bool looping); static hx::ObjectPtr< AudioChannel_obj > __alloc(hx::Ctx *_hx_ctx,bool looping); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~AudioChannel_obj(); HX_DO_RTTI_ALL; hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp); hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); bool _hx_isInstanceOf(int inClassId); void *_hx_getInterface(int inHash); ::String __ToString() const { return HX_HCSTRING("AudioChannel","\xad","\x62","\x5f","\xa0"); } ::kha::arrays::Float32ArrayPrivate data; Float myVolume; int myPosition; bool paused; bool looping; void nextSamples( ::kha::arrays::Float32ArrayPrivate samples,int length,int sampleRate); ::Dynamic nextSamples_dyn(); void play(); ::Dynamic play_dyn(); void pause(); ::Dynamic pause_dyn(); void stop(); ::Dynamic stop_dyn(); Float length; Float get_length(); ::Dynamic get_length_dyn(); Float position; Float get_position(); ::Dynamic get_position_dyn(); Float get_volume(); ::Dynamic get_volume_dyn(); Float set_volume(Float value); ::Dynamic set_volume_dyn(); bool finished; bool get_finished(); ::Dynamic get_finished_dyn(); }; } // end namespace kha } // end namespace audio2 #endif /* INCLUDED_kha_audio2_AudioChannel */
[ "neverliberty@gmail.com" ]
neverliberty@gmail.com
56b0b100590bb26c21557bc88608772a8024a59a
54e6cdf04c19da9815c3d939be2fea408cc82cc7
/game_logic_test/src/frenzy_spell_test_suite.cpp
de83e0547a2214c5ede1f35492b9fddc2cbf1f2d
[]
no_license
andyprowl/snake-overflow
0ef73f799e6c2ade25af7c9936da94ea3fa36b29
027b64ccb2562b5253e89df29bd42b61185b9145
refs/heads/master
2021-01-13T02:08:34.352229
2015-04-15T21:28:21
2015-04-15T21:28:21
32,992,332
3
0
null
null
null
null
UTF-8
C++
false
false
2,532
cpp
#include "stdafx.hpp" #include "snake_overflow/frenzy_spell.hpp" #include "snake_overflow/testing/cube_terrain_game_fixture.hpp" #include "util/repeat.hpp" namespace snake_overflow { namespace testing { using ::testing::Eq; class FrenzySpell : public CubeTerrainGameFixture { protected: virtual void SetUp() override { CubeTerrainGameFixture::SetUp(); this->the_spell = std::make_unique<frenzy_spell>(this->lifetime); } protected: int lifetime = 5; std::unique_ptr<frenzy_spell> the_spell; }; TEST_THAT(FrenzySpell, WHAT(Affect), WHEN(GivenASnakeToWhichTheSpellWasAddedWithLowerThanMaximumSpeed), THEN(IncrementsItsSpeedForANumberOfUpdatesEqualToTheLifetimeOfTheSpell)) { auto& s = get_snake(); auto added_spell = this->the_spell.get(); s.add_spell(std::move(this->the_spell)); auto const initial_speed = s.speed; util::repeat(this->lifetime - 1, [added_spell, initial_speed, &s] { added_spell->affect(s); EXPECT_THAT(s.speed, Eq(initial_speed + 1)); }); added_spell->affect(s); EXPECT_THAT(s.speed, Eq(initial_speed)); } TEST_THAT(FrenzySpell, WHAT(Affect), WHEN(GivenASnakeToWhichTheSpellWasAddedWithMaximumSpeed), THEN(DoesNotIncrementItsSpeed)) { auto& s = get_snake(); auto const maximum_speed = *(s.speed.maximum_value); s.speed = maximum_speed; auto added_spell = this->the_spell.get(); s.add_spell(std::move(this->the_spell)); added_spell->affect(s); EXPECT_THAT(s.speed, Eq(maximum_speed)); } TEST_THAT(FrenzySpell, WHAT(Affect), WHEN(WhenTheSpellLifetimeExpiresAndSpeedOfGivenSnakeWasNeverIncremented), THEN(DoesNotDecrementTheSpeedOfThatSnake)) { auto& s = get_snake(); auto const maximum_speed = *(s.speed.maximum_value); s.speed = maximum_speed; auto added_spell = this->the_spell.get(); s.add_spell(std::move(this->the_spell)); util::repeat(this->lifetime, [added_spell, &s] { added_spell->affect(s); }); EXPECT_THAT(s.speed, Eq(maximum_speed)); } TEST_THAT(FrenzySpell, WHAT(Affect), WHEN(WhenTheLifetimeOfTheSpellReachesZero), THEN(RemovesSelfFromTheSnake)) { auto& s = get_snake(); auto added_spell = this->the_spell.get(); s.add_spell(std::move(this->the_spell)); util::repeat(this->lifetime, [added_spell, &s] { added_spell->affect(s); }); auto const spells = s.get_all_spells(); EXPECT_TRUE(spells.empty()); } } }
[ "andy.prowl@gmail.com" ]
andy.prowl@gmail.com
e61d1b70ebe7ef465e0ad883c18c3b5ef4c1c504
ee3b729491915834f69ea4f1e06b0221b81a4c14
/libraries/DHT_sensor_library/examples/DHT_Unified_Sensor/Programa_ejemplo_esp_8266_STA.ino.ino
426fe6f62a98ce6b8a5b5eac3b8a6cde117f20d4
[]
no_license
LopLuAl/Arduino-Clase
64fa01d31f236d69b76fe102809609205aba177a
ed96b004114cf52f9f39e19195edb1ebf827253b
refs/heads/master
2023-03-31T08:57:06.360551
2021-04-06T00:48:32
2021-04-06T00:48:32
346,533,552
0
0
null
null
null
null
UTF-8
C++
false
false
739
ino
#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char *ssid_STA = "Fibertel WiFi017 2.4GHz"; const char *password_STA = "0102017365"; ESP8266WebServer server(80); void setup() { Serial.begin(115200); delay(10); Serial.println(); WiFi.mode(WIFI_STA); WiFi.begin(ssid_STA, password_STA); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } WiFi.setAutoReconnect(true); Serial.println("WiFi conectada."); Serial.println(); WiFi.printDiag(Serial); Serial.println(); Serial.print("STA dirección IP: "); Serial.println(WiFi.localIP()); server.on("/", [](){ server.send(200, "text/plain", "Hola mundo!!"); }); server.begin(); Serial.println("Servidor inicializado."); } void loop() { server.handleClient();}
[ "lucianlopez@frba.utn.edu.ar" ]
lucianlopez@frba.utn.edu.ar
4c8f2f7fb4cd1d524bf00c1fac2c87bc1d55191c
f1dcd8cf35663b3affd3e19d32ea27355ad93fd2
/libthread_safe/include/thread_safe/gnu/c++/9/tr1/hashtable.h
82862edbc9d7ecbfc22a8f7b6427c5149bc36e01
[]
no_license
mgood7123/greenThreads
eb65665b9403cfc51c68dfd95e1ebac87eed96cd
891ac222fa6eb6bcbd44d51d370ac1d059d6a50d
refs/heads/master
2020-08-28T21:59:45.993320
2019-11-27T12:31:56
2019-11-27T12:31:56
217,831,766
0
0
null
null
null
null
UTF-8
C++
false
false
41,562
h
// TR1 hashtable.h header -*- C++ -*- // Copyright (C) 2007-2019 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file tr1/hashtable.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. * @headername{tr1/unordered_set, tr1/unordered_map} */ #ifndef _GLIBCXX_TR1_HASHTABLE_H #define _GLIBCXX_TR1_HASHTABLE_H 1 #pragma GCC system_header #include "../../tr1/hashtable_policy.h" namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr1 { // Class template _Hashtable, class definition. // Meaning of class template _Hashtable's template parameters // _Key and _Value: arbitrary CopyConstructible types. // _Allocator: an allocator type ([lib.allocator.requirements]) whose // value type is Value. As a conforming extension, we allow for // value type != Value. // _ExtractKey: function object that takes a object of type Value // and returns a value of type _Key. // _Equal: function object that takes two objects of type k and returns // a bool-like value that is true if the two objects are considered equal. // _H1: the hash function. A unary function object with argument type // Key and result type size_t. Return values should be distributed // over the entire range [0, numeric_limits<size_t>:::max()]. // _H2: the range-hashing function (in the terminology of Tavori and // Dreizin). A binary function object whose argument types and result // type are all size_t. Given arguments r and N, the return value is // in the range [0, N). // _Hash: the ranged hash function (Tavori and Dreizin). A binary function // whose argument types are _Key and size_t and whose result type is // size_t. Given arguments k and N, the return value is in the range // [0, N). Default: hash(k, N) = h2(h1(k), N). If _Hash is anything other // than the default, _H1 and _H2 are ignored. // _RehashPolicy: Policy class with three members, all of which govern // the bucket count. _M_next_bkt(n) returns a bucket count no smaller // than n. _M_bkt_for_elements(n) returns a bucket count appropriate // for an element count of n. _M_need_rehash(n_bkt, n_elt, n_ins) // determines whether, if the current bucket count is n_bkt and the // current element count is n_elt, we need to increase the bucket // count. If so, returns make_pair(true, n), where n is the new // bucket count. If not, returns make_pair(false, <anything>). // ??? Right now it is hard-wired that the number of buckets never // shrinks. Should we allow _RehashPolicy to change that? // __cache_hash_code: bool. true if we store the value of the hash // function along with the value. This is a time-space tradeoff. // Storing it may improve lookup speed by reducing the number of times // we need to call the Equal function. // __constant_iterators: bool. true if iterator and const_iterator are // both constant iterator types. This is true for unordered_set and // unordered_multiset, false for unordered_map and unordered_multimap. // __unique_keys: bool. true if the return value of _Hashtable::count(k) // is always at most one, false if it may be an arbitrary number. This // true for unordered_set and unordered_map, false for unordered_multiset // and unordered_multimap. template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __cache_hash_code, bool __constant_iterators, bool __unique_keys> class _Hashtable : public __detail::_Rehash_base<_RehashPolicy, _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys> >, public __detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, __cache_hash_code>, public __detail::_Map_base<_Key, _Value, _ExtractKey, __unique_keys, _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys> > { public: typedef _Allocator allocator_type; typedef _Value value_type; typedef _Key key_type; typedef _Equal key_equal; // mapped_type, if present, comes from _Map_base. // hasher, if present, comes from _Hash_code_base. typedef typename _Allocator::difference_type difference_type; typedef typename _Allocator::size_type size_type; typedef typename _Allocator::pointer pointer; typedef typename _Allocator::const_pointer const_pointer; typedef typename _Allocator::reference reference; typedef typename _Allocator::const_reference const_reference; typedef __detail::_Node_iterator<value_type, __constant_iterators, __cache_hash_code> local_iterator; typedef __detail::_Node_const_iterator<value_type, __constant_iterators, __cache_hash_code> const_local_iterator; typedef __detail::_Hashtable_iterator<value_type, __constant_iterators, __cache_hash_code> iterator; typedef __detail::_Hashtable_const_iterator<value_type, __constant_iterators, __cache_hash_code> const_iterator; template<typename _Key2, typename _Value2, typename _Ex2, bool __unique2, typename _Hashtable2> friend struct __detail::_Map_base; private: typedef __detail::_Hash_node<_Value, __cache_hash_code> _Node; typedef typename _Allocator::template rebind<_Node>::other _Node_allocator_type; typedef typename _Allocator::template rebind<_Node*>::other _Bucket_allocator_type; typedef typename _Allocator::template rebind<_Value>::other _Value_allocator_type; _Node_allocator_type _M_node_allocator; _Node** _M_buckets; size_type _M_bucket_count; size_type _M_element_count; _RehashPolicy _M_rehash_policy; _Node* _M_allocate_node(const value_type& __v); void _M_deallocate_node(_Node* __n); void _M_deallocate_nodes(_Node**, size_type); _Node** _M_allocate_buckets(size_type __n); void _M_deallocate_buckets(_Node**, size_type __n); public: // Constructor, destructor, assignment, swap _Hashtable(size_type __bucket_hint, const _H1&, const _H2&, const _Hash&, const _Equal&, const _ExtractKey&, const allocator_type&); template<typename _InputIterator> _Hashtable(_InputIterator __first, _InputIterator __last, size_type __bucket_hint, const _H1&, const _H2&, const _Hash&, const _Equal&, const _ExtractKey&, const allocator_type&); _Hashtable(const _Hashtable&); _Hashtable& operator=(const _Hashtable&); ~_Hashtable(); void swap(_Hashtable&); // Basic container operations iterator begin() { iterator __i(_M_buckets); if (!__i._M_cur_node) __i._M_incr_bucket(); return __i; } const_iterator begin() const { const_iterator __i(_M_buckets); if (!__i._M_cur_node) __i._M_incr_bucket(); return __i; } iterator end() { return iterator(_M_buckets + _M_bucket_count); } const_iterator end() const { return const_iterator(_M_buckets + _M_bucket_count); } size_type size() const { return _M_element_count; } _GLIBCXX_NODISCARD bool empty() const { return size() == 0; } allocator_type get_allocator() const { return allocator_type(_M_node_allocator); } _Value_allocator_type _M_get_Value_allocator() const { return _Value_allocator_type(_M_node_allocator); } size_type max_size() const { return _M_node_allocator.max_size(); } // Observers key_equal key_eq() const { return this->_M_eq; } // hash_function, if present, comes from _Hash_code_base. // Bucket operations size_type bucket_count() const { return _M_bucket_count; } size_type max_bucket_count() const { return max_size(); } size_type bucket_size(size_type __n) const { return std::distance(begin(__n), end(__n)); } size_type bucket(const key_type& __k) const { return this->_M_bucket_index(__k, this->_M_hash_code(__k), bucket_count()); } local_iterator begin(size_type __n) { return local_iterator(_M_buckets[__n]); } local_iterator end(size_type) { return local_iterator(0); } const_local_iterator begin(size_type __n) const { return const_local_iterator(_M_buckets[__n]); } const_local_iterator end(size_type) const { return const_local_iterator(0); } float load_factor() const { return static_cast<float>(size()) / static_cast<float>(bucket_count()); } // max_load_factor, if present, comes from _Rehash_base. // Generalization of max_load_factor. Extension, not found in TR1. Only // useful if _RehashPolicy is something other than the default. const _RehashPolicy& __rehash_policy() const { return _M_rehash_policy; } void __rehash_policy(const _RehashPolicy&); // Lookup. iterator find(const key_type& __k); const_iterator find(const key_type& __k) const; size_type count(const key_type& __k) const; std::pair<iterator, iterator> equal_range(const key_type& __k); std::pair<const_iterator, const_iterator> equal_range(const key_type& __k) const; private: // Find, insert and erase helper functions // ??? This dispatching is a workaround for the fact that we don't // have partial specialization of member templates; it would be // better to just specialize insert on __unique_keys. There may be a // cleaner workaround. typedef typename __gnu_cxx::__conditional_type<__unique_keys, std::pair<iterator, bool>, iterator>::__type _Insert_Return_Type; typedef typename __gnu_cxx::__conditional_type<__unique_keys, std::_Select1st<_Insert_Return_Type>, std::_Identity<_Insert_Return_Type> >::__type _Insert_Conv_Type; _Node* _M_find_node(_Node*, const key_type&, typename _Hashtable::_Hash_code_type) const; iterator _M_insert_bucket(const value_type&, size_type, typename _Hashtable::_Hash_code_type); std::pair<iterator, bool> _M_insert(const value_type&, std::tr1::true_type); iterator _M_insert(const value_type&, std::tr1::false_type); void _M_erase_node(_Node*, _Node**); public: // Insert and erase _Insert_Return_Type insert(const value_type& __v) { return _M_insert(__v, std::tr1::integral_constant<bool, __unique_keys>()); } iterator insert(iterator, const value_type& __v) { return iterator(_Insert_Conv_Type()(this->insert(__v))); } const_iterator insert(const_iterator, const value_type& __v) { return const_iterator(_Insert_Conv_Type()(this->insert(__v))); } template<typename _InputIterator> void insert(_InputIterator __first, _InputIterator __last); iterator erase(iterator); const_iterator erase(const_iterator); size_type erase(const key_type&); iterator erase(iterator, iterator); const_iterator erase(const_iterator, const_iterator); void clear(); // Set number of buckets to be appropriate for container of n element. void rehash(size_type __n); private: // Unconditionally change size of bucket array to n. void _M_rehash(size_type __n); }; // Definitions of class template _Hashtable's out-of-line member functions. template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::_Node* _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_allocate_node(const value_type& __v) { _Node* __n = _M_node_allocator.allocate(1); __try { _M_get_Value_allocator().construct(&__n->_M_v, __v); __n->_M_next = 0; return __n; } __catch(...) { _M_node_allocator.deallocate(__n, 1); __throw_exception_again; } } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_deallocate_node(_Node* __n) { _M_get_Value_allocator().destroy(&__n->_M_v); _M_node_allocator.deallocate(__n, 1); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_deallocate_nodes(_Node** __array, size_type __n) { for (size_type __i = 0; __i < __n; ++__i) { _Node* __p = __array[__i]; while (__p) { _Node* __tmp = __p; __p = __p->_M_next; _M_deallocate_node(__tmp); } __array[__i] = 0; } } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::_Node** _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_allocate_buckets(size_type __n) { _Bucket_allocator_type __alloc(_M_node_allocator); // We allocate one extra bucket to hold a sentinel, an arbitrary // non-null pointer. Iterator increment relies on this. _Node** __p = __alloc.allocate(__n + 1); std::fill(__p, __p + __n, (_Node*) 0); __p[__n] = reinterpret_cast<_Node*>(0x1000); return __p; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_deallocate_buckets(_Node** __p, size_type __n) { _Bucket_allocator_type __alloc(_M_node_allocator); __alloc.deallocate(__p, __n + 1); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _Hashtable(size_type __bucket_hint, const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : __detail::_Rehash_base<_RehashPolicy, _Hashtable>(), __detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, __chc>(__exk, __eq, __h1, __h2, __h), __detail::_Map_base<_Key, _Value, _ExtractKey, __uk, _Hashtable>(), _M_node_allocator(__a), _M_bucket_count(0), _M_element_count(0), _M_rehash_policy() { _M_bucket_count = _M_rehash_policy._M_next_bkt(__bucket_hint); _M_buckets = _M_allocate_buckets(_M_bucket_count); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> template<typename _InputIterator> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _Hashtable(_InputIterator __f, _InputIterator __l, size_type __bucket_hint, const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : __detail::_Rehash_base<_RehashPolicy, _Hashtable>(), __detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, __chc>(__exk, __eq, __h1, __h2, __h), __detail::_Map_base<_Key, _Value, _ExtractKey, __uk, _Hashtable>(), _M_node_allocator(__a), _M_bucket_count(0), _M_element_count(0), _M_rehash_policy() { _M_bucket_count = std::max(_M_rehash_policy._M_next_bkt(__bucket_hint), _M_rehash_policy. _M_bkt_for_elements(__detail:: __distance_fw(__f, __l))); _M_buckets = _M_allocate_buckets(_M_bucket_count); __try { for (; __f != __l; ++__f) this->insert(*__f); } __catch(...) { clear(); _M_deallocate_buckets(_M_buckets, _M_bucket_count); __throw_exception_again; } } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _Hashtable(const _Hashtable& __ht) : __detail::_Rehash_base<_RehashPolicy, _Hashtable>(__ht), __detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, __chc>(__ht), __detail::_Map_base<_Key, _Value, _ExtractKey, __uk, _Hashtable>(__ht), _M_node_allocator(__ht._M_node_allocator), _M_bucket_count(__ht._M_bucket_count), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { _M_buckets = _M_allocate_buckets(_M_bucket_count); __try { for (size_type __i = 0; __i < __ht._M_bucket_count; ++__i) { _Node* __n = __ht._M_buckets[__i]; _Node** __tail = _M_buckets + __i; while (__n) { *__tail = _M_allocate_node(__n->_M_v); this->_M_copy_code(*__tail, __n); __tail = &((*__tail)->_M_next); __n = __n->_M_next; } } } __catch(...) { clear(); _M_deallocate_buckets(_M_buckets, _M_bucket_count); __throw_exception_again; } } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>& _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: operator=(const _Hashtable& __ht) { _Hashtable __tmp(__ht); this->swap(__tmp); return *this; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: ~_Hashtable() { clear(); _M_deallocate_buckets(_M_buckets, _M_bucket_count); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: swap(_Hashtable& __x) { // The only base class with member variables is hash_code_base. We // define _Hash_code_base::_M_swap because different specializations // have different members. __detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, __chc>::_M_swap(__x); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 431. Swapping containers with unequal allocators. std::__alloc_swap<_Node_allocator_type>::_S_do_it(_M_node_allocator, __x._M_node_allocator); std::swap(_M_rehash_policy, __x._M_rehash_policy); std::swap(_M_buckets, __x._M_buckets); std::swap(_M_bucket_count, __x._M_bucket_count); std::swap(_M_element_count, __x._M_element_count); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: __rehash_policy(const _RehashPolicy& __pol) { _M_rehash_policy = __pol; size_type __n_bkt = __pol._M_bkt_for_elements(_M_element_count); if (__n_bkt > _M_bucket_count) _M_rehash(__n_bkt); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: find(const key_type& __k) { typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); std::size_t __n = this->_M_bucket_index(__k, __code, _M_bucket_count); _Node* __p = _M_find_node(_M_buckets[__n], __k, __code); return __p ? iterator(__p, _M_buckets + __n) : this->end(); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::const_iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: find(const key_type& __k) const { typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); std::size_t __n = this->_M_bucket_index(__k, __code, _M_bucket_count); _Node* __p = _M_find_node(_M_buckets[__n], __k, __code); return __p ? const_iterator(__p, _M_buckets + __n) : this->end(); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::size_type _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: count(const key_type& __k) const { typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); std::size_t __n = this->_M_bucket_index(__k, __code, _M_bucket_count); std::size_t __result = 0; for (_Node* __p = _M_buckets[__n]; __p; __p = __p->_M_next) if (this->_M_compare(__k, __code, __p)) ++__result; return __result; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> std::pair<typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator, typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: equal_range(const key_type& __k) { typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); std::size_t __n = this->_M_bucket_index(__k, __code, _M_bucket_count); _Node** __head = _M_buckets + __n; _Node* __p = _M_find_node(*__head, __k, __code); if (__p) { _Node* __p1 = __p->_M_next; for (; __p1; __p1 = __p1->_M_next) if (!this->_M_compare(__k, __code, __p1)) break; iterator __first(__p, __head); iterator __last(__p1, __head); if (!__p1) __last._M_incr_bucket(); return std::make_pair(__first, __last); } else return std::make_pair(this->end(), this->end()); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> std::pair<typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::const_iterator, typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::const_iterator> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: equal_range(const key_type& __k) const { typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); std::size_t __n = this->_M_bucket_index(__k, __code, _M_bucket_count); _Node** __head = _M_buckets + __n; _Node* __p = _M_find_node(*__head, __k, __code); if (__p) { _Node* __p1 = __p->_M_next; for (; __p1; __p1 = __p1->_M_next) if (!this->_M_compare(__k, __code, __p1)) break; const_iterator __first(__p, __head); const_iterator __last(__p1, __head); if (!__p1) __last._M_incr_bucket(); return std::make_pair(__first, __last); } else return std::make_pair(this->end(), this->end()); } // Find the node whose key compares equal to k, beginning the search // at p (usually the head of a bucket). Return zero if no node is found. template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::_Node* _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_find_node(_Node* __p, const key_type& __k, typename _Hashtable::_Hash_code_type __code) const { for (; __p; __p = __p->_M_next) if (this->_M_compare(__k, __code, __p)) return __p; return 0; } // Insert v in bucket n (assumes no element with its key already present). template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_insert_bucket(const value_type& __v, size_type __n, typename _Hashtable::_Hash_code_type __code) { std::pair<bool, std::size_t> __do_rehash = _M_rehash_policy._M_need_rehash(_M_bucket_count, _M_element_count, 1); // Allocate the new node before doing the rehash so that we don't // do a rehash if the allocation throws. _Node* __new_node = _M_allocate_node(__v); __try { if (__do_rehash.first) { const key_type& __k = this->_M_extract(__v); __n = this->_M_bucket_index(__k, __code, __do_rehash.second); _M_rehash(__do_rehash.second); } __new_node->_M_next = _M_buckets[__n]; this->_M_store_code(__new_node, __code); _M_buckets[__n] = __new_node; ++_M_element_count; return iterator(__new_node, _M_buckets + __n); } __catch(...) { _M_deallocate_node(__new_node); __throw_exception_again; } } // Insert v if no element with its key is already present. template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> std::pair<typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator, bool> _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_insert(const value_type& __v, std::tr1::true_type) { const key_type& __k = this->_M_extract(__v); typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); size_type __n = this->_M_bucket_index(__k, __code, _M_bucket_count); if (_Node* __p = _M_find_node(_M_buckets[__n], __k, __code)) return std::make_pair(iterator(__p, _M_buckets + __n), false); return std::make_pair(_M_insert_bucket(__v, __n, __code), true); } // Insert v unconditionally. template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_insert(const value_type& __v, std::tr1::false_type) { std::pair<bool, std::size_t> __do_rehash = _M_rehash_policy._M_need_rehash(_M_bucket_count, _M_element_count, 1); if (__do_rehash.first) _M_rehash(__do_rehash.second); const key_type& __k = this->_M_extract(__v); typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); size_type __n = this->_M_bucket_index(__k, __code, _M_bucket_count); // First find the node, avoid leaking new_node if compare throws. _Node* __prev = _M_find_node(_M_buckets[__n], __k, __code); _Node* __new_node = _M_allocate_node(__v); if (__prev) { __new_node->_M_next = __prev->_M_next; __prev->_M_next = __new_node; } else { __new_node->_M_next = _M_buckets[__n]; _M_buckets[__n] = __new_node; } this->_M_store_code(__new_node, __code); ++_M_element_count; return iterator(__new_node, _M_buckets + __n); } // For erase(iterator) and erase(const_iterator). template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_erase_node(_Node* __p, _Node** __b) { _Node* __cur = *__b; if (__cur == __p) *__b = __cur->_M_next; else { _Node* __next = __cur->_M_next; while (__next != __p) { __cur = __next; __next = __cur->_M_next; } __cur->_M_next = __next->_M_next; } _M_deallocate_node(__p); --_M_element_count; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> template<typename _InputIterator> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: insert(_InputIterator __first, _InputIterator __last) { size_type __n_elt = __detail::__distance_fw(__first, __last); std::pair<bool, std::size_t> __do_rehash = _M_rehash_policy._M_need_rehash(_M_bucket_count, _M_element_count, __n_elt); if (__do_rehash.first) _M_rehash(__do_rehash.second); for (; __first != __last; ++__first) this->insert(*__first); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: erase(iterator __it) { iterator __result = __it; ++__result; _M_erase_node(__it._M_cur_node, __it._M_cur_bucket); return __result; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::const_iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: erase(const_iterator __it) { const_iterator __result = __it; ++__result; _M_erase_node(__it._M_cur_node, __it._M_cur_bucket); return __result; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::size_type _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: erase(const key_type& __k) { typename _Hashtable::_Hash_code_type __code = this->_M_hash_code(__k); std::size_t __n = this->_M_bucket_index(__k, __code, _M_bucket_count); size_type __result = 0; _Node** __slot = _M_buckets + __n; while (*__slot && !this->_M_compare(__k, __code, *__slot)) __slot = &((*__slot)->_M_next); _Node** __saved_slot = 0; while (*__slot && this->_M_compare(__k, __code, *__slot)) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 526. Is it undefined if a function in the standard changes // in parameters? if (&this->_M_extract((*__slot)->_M_v) != &__k) { _Node* __p = *__slot; *__slot = __p->_M_next; _M_deallocate_node(__p); --_M_element_count; ++__result; } else { __saved_slot = __slot; __slot = &((*__slot)->_M_next); } } if (__saved_slot) { _Node* __p = *__saved_slot; *__saved_slot = __p->_M_next; _M_deallocate_node(__p); --_M_element_count; ++__result; } return __result; } // ??? This could be optimized by taking advantage of the bucket // structure, but it's not clear that it's worth doing. It probably // wouldn't even be an optimization unless the load factor is large. template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: erase(iterator __first, iterator __last) { while (__first != __last) __first = this->erase(__first); return __last; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> typename _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>::const_iterator _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: erase(const_iterator __first, const_iterator __last) { while (__first != __last) __first = this->erase(__first); return __last; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: clear() { _M_deallocate_nodes(_M_buckets, _M_bucket_count); _M_element_count = 0; } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: rehash(size_type __n) { _M_rehash(std::max(_M_rehash_policy._M_next_bkt(__n), _M_rehash_policy._M_bkt_for_elements(_M_element_count + 1))); } template<typename _Key, typename _Value, typename _Allocator, typename _ExtractKey, typename _Equal, typename _H1, typename _H2, typename _Hash, typename _RehashPolicy, bool __chc, bool __cit, bool __uk> void _Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __chc, __cit, __uk>:: _M_rehash(size_type __n) { _Node** __new_array = _M_allocate_buckets(__n); __try { for (size_type __i = 0; __i < _M_bucket_count; ++__i) while (_Node* __p = _M_buckets[__i]) { std::size_t __new_index = this->_M_bucket_index(__p, __n); _M_buckets[__i] = __p->_M_next; __p->_M_next = __new_array[__new_index]; __new_array[__new_index] = __p; } _M_deallocate_buckets(_M_buckets, _M_bucket_count); _M_bucket_count = __n; _M_buckets = __new_array; } __catch(...) { // A failure here means that a hash function threw an exception. // We can't restore the previous state without calling the hash // function again, so the only sensible recovery is to delete // everything. _M_deallocate_nodes(__new_array, __n); _M_deallocate_buckets(__new_array, __n); _M_deallocate_nodes(_M_buckets, _M_bucket_count); _M_element_count = 0; __throw_exception_again; } } } // namespace tr1 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _GLIBCXX_TR1_HASHTABLE_H
[ "smallville7123" ]
smallville7123
3c5012918a8971218428dedafeec6eee08a52c64
fb9072766af958a8f977f9368bfed536fab2d681
/Upper/Upper/ParaSetDlg.h
eaa45417b51319958e0ce8d13d7a45beb451c5de
[]
no_license
MaJLhdkj/HD3025
63def956b8f6f0e529146354e0d12b98ce05bc88
24c8041c0d91202bde21115cd43575c5528d8509
refs/heads/master
2021-01-25T10:16:16.280906
2014-01-21T04:16:57
2014-01-21T04:16:57
16,092,472
1
0
null
null
null
null
GB18030
C++
false
false
517
h
#pragma once #include "SizeAdjust.h" // CParaSetDlg 对话框 class CParaSetDlg : public CDialogEx { DECLARE_DYNAMIC(CParaSetDlg) public: CParaSetDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CParaSetDlg(); // 对话框数据 enum { IDD = IDD_DLG_PARASET }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnSize(UINT nType, int cx, int cy); virtual BOOL OnInitDialog(); CFont m_ParaFont1; CFont m_ParaFont2; };
[ "yunxiangtju@163.com" ]
yunxiangtju@163.com
232043d7c8c149c26d8fd0f2d0f30b251df5d3a0
9e2dbb3f8205f8bd0b3b5d79261182e9fb4c32c4
/C++ codes/Examples and Labs/products.cpp
2fdb67625f47abad4a6e84f30dc270078baa0214
[]
no_license
melody40/monorepo
87129f934066cd1e162d578f8e4950e12b0fa54d
fc5b7c8da70534e69d55770adebf308fd41c02b7
refs/heads/master
2022-12-22T22:49:01.277092
2020-09-21T17:20:43
2020-09-21T18:35:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
408
cpp
#include <iostream> #include <conio.h> using namespace std; int main () { int a[100]; int b; cin>> b; int i; int j=0; for ( i=1;i<=b;i++ ) { if ( b%i==0 ) { a[j] = i; j++; } } for ( i=0;i<j;i++ ) { cout<< a[i]<< " "; } getch (); return 0; }
[ "torshobuet@gmail.com" ]
torshobuet@gmail.com
4332373ca62a361a61b07e191562e9119a943486
a843cc668ce1b67a7b88a6dd257567741804165a
/lv3/path/std/works/differtest.cpp
8a3740f98d9d80a7f4deb25bccea99ee0b4bdfe9
[]
no_license
yuxaij/noip_ro
53aff24527550ae432d1eaf5c41238f7149a070a
661636f5b829255b5d2019225b9fb28d0fde7b51
refs/heads/master
2022-03-06T15:05:06.137717
2019-11-06T02:14:12
2019-11-06T02:14:12
218,312,461
0
0
null
null
null
null
UTF-8
C++
false
false
323
cpp
#include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; int a[5000010]; int cnt = 0; int main() { int x; while(scanf("%d", &x) != EOF) a[++cnt] = x; sort(a + 1, a + cnt + 1); int diffs = unique(a + 1, a + cnt + 1) - a - 1; cout << diffs << endl; }
[ "yuxaij@gmail.com" ]
yuxaij@gmail.com
26052ed065c5987ba65cebbc3635136ff27ace70
df88fe7229c70e2fdc7f1a138545eca51930d813
/src/gemm/cblas.cpp
76b20a6b5f4406800a688d4810e8ed6397ef4cae
[]
no_license
simongdg/microbench
5a3a3436ac7b5d17448f2fee7b56040a28f358a1
135c6a89a53c3697a929c96d53686f88b8487370
refs/heads/master
2020-03-19T21:31:58.834979
2018-06-06T21:33:37
2018-06-06T21:33:37
112,533,314
0
0
null
2017-11-29T22:06:00
2017-11-29T22:05:59
null
UTF-8
C++
false
false
4,753
cpp
#include <benchmark/benchmark.h> #include <complex> #include <iostream> #include <numeric> #include <stdio.h> #include <stdlib.h> #include <vector> #include <cblas.h> #include "utils/utils.hpp" #include "gemm/args.hpp" #include "gemm/utils.hpp" template <typename T> static void cblas_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const T alpha, const T* A, const T* B, const T beta, T* C); template <> void cblas_gemm<float>(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float* A, const float* B, const float beta, float* C) { const int lda = (TransA == CblasNoTrans) ? K : M; const int ldb = (TransB == CblasNoTrans) ? N : K; cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, N); } template <> void cblas_gemm<double>(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double* A, const double* B, const double beta, double* C) { const int lda = (TransA == CblasNoTrans) ? K : M; const int ldb = (TransB == CblasNoTrans) ? N : K; cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, N); } template <> void cblas_gemm<std::complex<float>>(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const std::complex<float> alpha, const std::complex<float>* A, const std::complex<float>* B, const std::complex<float> beta, std::complex<float>* C) { using scalar_type = float; const int lda = (TransA == CblasNoTrans) ? K : M; const int ldb = (TransB == CblasNoTrans) ? N : K; cblas_cgemm(CblasRowMajor, TransA, TransB, M, N, K, reinterpret_cast<const scalar_type(&)[2]>(alpha), reinterpret_cast<const scalar_type*>(A), lda, reinterpret_cast<const scalar_type*>(B), ldb, reinterpret_cast<const scalar_type(&)[2]>(beta), reinterpret_cast<scalar_type*>(C), N); } template <> void cblas_gemm<std::complex<double>>(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const std::complex<double> alpha, const std::complex<double>* A, const std::complex<double>* B, const std::complex<double> beta, std::complex<double>* C) { using scalar_type = double; const int lda = (TransA == CblasNoTrans) ? K : M; const int ldb = (TransB == CblasNoTrans) ? N : K; cblas_zgemm(CblasRowMajor, TransA, TransB, M, N, K, reinterpret_cast<const scalar_type(&)[2]>(alpha), reinterpret_cast<const scalar_type*>(A), lda, reinterpret_cast<const scalar_type*>(B), ldb, reinterpret_cast<const scalar_type(&)[2]>(beta), reinterpret_cast<scalar_type*>(C), N); } template <typename T> static void CBLAS(benchmark::State& state) { static const std::string IMPLEMENTATION_NAME = gemm::detail::implementation_name<T>(); state.SetLabel(fmt::format("CBLAS/{}", IMPLEMENTATION_NAME)); const T one = gemm::detail::one<T>(); const T zero = gemm::detail::zero<T>(); const auto M = state.range(0); const auto N = state.range(1); const auto K = state.range(2); T alpha{one}; T beta{zero}; auto a = std::vector<T>(M * K); auto b = std::vector<T>(K * N); auto c = std::vector<T>(M * N); std::fill(a.begin(), a.end(), one); std::fill(b.begin(), b.end(), one); std::fill(c.begin(), c.end(), zero); for (auto _ : state) { cblas_gemm<T>(CblasNoTrans, CblasNoTrans, M, N, K, alpha, a.data(), b.data(), beta, c.data()); benchmark::DoNotOptimize(c.data()); } state.counters.insert( {{"M", M}, {"N", N}, {"K", K}, {"Flops", {2.0 * M * N * K, benchmark::Counter::kAvgThreadsRate}}}); state.SetBytesProcessed(int64_t(state.iterations()) * a.size() * b.size() * c.size()); state.SetItemsProcessed(int64_t(state.iterations()) * M * N * K); } static void CBLAS_SGEMM(benchmark::State& state) { return CBLAS<float>(state); } static void CBLAS_DGEMM(benchmark::State& state) { return CBLAS<double>(state); } static void CBLAS_CGEMM(benchmark::State& state) { return CBLAS<std::complex<float>>(state); } static void CBLAS_ZGEMM(benchmark::State& state) { return CBLAS<std::complex<double>>(state); } // BENCHMARK(CBLAS_SGEMM)->ALL_ARGS(); // BENCHMARK(CBLAS_DGEMM)->ALL_ARGS(); // BENCHMARK(CBLAS_CGEMM)->ALL_ARGS(); // BENCHMARK(CBLAS_ZGEMM)->ALL_ARGS();
[ "abduld@wolfram.com" ]
abduld@wolfram.com
b499bc262329d1a20a5da457a90cd44243ebfa67
cefd6c17774b5c94240d57adccef57d9bba4a2e9
/WebKit/Source/WebCore/bridge/jsc/BridgeJSC.h
d397f87375f9d33e55ecd3086bea64cd5102032c
[ "BSL-1.0", "BSD-2-Clause", "LGPL-2.0-only", "LGPL-2.1-only" ]
permissive
adzhou/oragle
9c054c25b24ff0a65cb9639bafd02aac2bcdce8b
5442d418b87d0da161429ffa5cb83777e9b38e4d
refs/heads/master
2022-11-01T05:04:59.368831
2014-03-12T15:50:08
2014-03-12T15:50:08
17,238,063
0
1
BSL-1.0
2022-10-18T04:23:53
2014-02-27T05:39:44
C++
UTF-8
C++
false
false
4,590
h
/* * Copyright (C) 2003, 2008, 2009 Apple Inc. All rights reserved. * Copyright 2010, The Android Open Source Project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BridgeJSC_h #define BridgeJSC_h #include "Bridge.h" #include <runtime/JSCInlines.h> #include <runtime/JSString.h> #include <wtf/HashMap.h> #include <wtf/RefCounted.h> #include <wtf/Vector.h> namespace JSC { class ArgList; class Identifier; class JSGlobalObject; class PropertyNameArray; class RuntimeMethod; namespace Bindings { class Instance; class Method; class RootObject; class RuntimeObject; class Field { public: virtual JSValue valueFromInstance(ExecState*, const Instance*) const = 0; virtual void setValueToInstance(ExecState*, const Instance*, JSValue) const = 0; virtual ~Field() { } }; class Class { WTF_MAKE_NONCOPYABLE(Class); WTF_MAKE_FAST_ALLOCATED; public: Class() { } virtual Method* methodNamed(PropertyName, Instance*) const = 0; virtual Field* fieldNamed(PropertyName, Instance*) const = 0; virtual JSValue fallbackObject(ExecState*, Instance*, PropertyName) { return jsUndefined(); } virtual ~Class() { } }; class Instance : public RefCounted<Instance> { public: Instance(PassRefPtr<RootObject>); // These functions are called before and after the main entry points into // the native implementations. They can be used to establish and cleanup // any needed state. void begin(); void end(); virtual Class* getClass() const = 0; JSObject* createRuntimeObject(ExecState*); void willInvalidateRuntimeObject(); // Returns false if the value was not set successfully. virtual bool setValueOfUndefinedField(ExecState*, PropertyName, JSValue) { return false; } virtual JSValue getMethod(ExecState*, PropertyName) = 0; virtual JSValue invokeMethod(ExecState*, RuntimeMethod* method) = 0; virtual bool supportsInvokeDefaultMethod() const { return false; } virtual JSValue invokeDefaultMethod(ExecState*) { return jsUndefined(); } virtual bool supportsConstruct() const { return false; } virtual JSValue invokeConstruct(ExecState*, const ArgList&) { return JSValue(); } virtual void getPropertyNames(ExecState*, PropertyNameArray&) { } virtual JSValue defaultValue(ExecState*, PreferredPrimitiveType) const = 0; virtual JSValue valueOf(ExecState* exec) const = 0; RootObject* rootObject() const; virtual ~Instance(); virtual bool getOwnPropertySlot(JSObject*, ExecState*, PropertyName, PropertySlot&) { return false; } virtual void put(JSObject*, ExecState*, PropertyName, JSValue, PutPropertySlot&) { } protected: virtual void virtualBegin() { } virtual void virtualEnd() { } virtual RuntimeObject* newRuntimeObject(ExecState*); RefPtr<RootObject> m_rootObject; private: Weak<RuntimeObject> m_runtimeObject; }; class Array { WTF_MAKE_NONCOPYABLE(Array); public: Array(PassRefPtr<RootObject>); virtual ~Array(); virtual void setValueAt(ExecState*, unsigned index, JSValue) const = 0; virtual JSValue valueAt(ExecState*, unsigned index) const = 0; virtual unsigned int getLength() const = 0; protected: RefPtr<RootObject> m_rootObject; }; const char* signatureForParameters(const ArgList&); } // namespace Bindings } // namespace JSC #endif
[ "adzhou@hp.com" ]
adzhou@hp.com
24e824284ca717431d0418e5c2f679af43cedbd1
07d1ac2af08007d940a108b15c3fdf5413141864
/test.cpp
f7341f88709852096ce9a88e29674a74de3cb0c4
[]
no_license
a798447431/Practice-Code
16edaac0abb2294282c8aeccc7204e8d4a1fda83
24b78c99117f700fc5860e28552914d10f89b03c
refs/heads/master
2020-12-27T10:17:08.148925
2020-02-03T01:58:39
2020-02-03T01:58:39
237,865,788
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
/************************************************************************* > File Name: test.cpp > Author: suziteng > Mail: 253604653@qq.com > Created Time: 2019年05月18日 星期六 16时44分33秒 ************************************************************************/ #include<gtest/gtest.h> int add(int a,int b){ return a+b; } TEST(testCase,test0){ EXPECT_EQ(add(2,3),4); } int main(int argc,char **argv){ testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
[ "253604653@qq.com" ]
253604653@qq.com
30ce8b489e27c285d3dbbde3bd8657d50549a4a7
7ebf122cf52f0412cd41b738382d7f7ebe8d1653
/ObjectLearn/src/Visualisation/GraphicsBase.cpp
6174cf1fa483f0019675a341e85633932b5b73d0
[]
no_license
osushkov/phd_src
bcb5e75ab839575dea07ef70a7d308dc3e649d04
1eb49671977442df4b17b332f8d345e751e4df99
refs/heads/master
2020-12-04T11:19:56.108003
2016-08-23T11:31:47
2016-08-23T11:31:47
66,361,170
0
0
null
null
null
null
UTF-8
C++
false
false
3,928
cpp
/* * GraphicsBase.cpp * * Created on: 22/06/2009 * Author: osushkov */ #include "GraphicsBase.h" #include <iostream> #include <GL/gl.h> #include <GL/glu.h> #include <SDL/SDL.h> #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 GraphicsBase& GraphicsBase::instance(void){ static GraphicsBase graphics_base; return graphics_base; } GraphicsBase::GraphicsBase(){ is_initialised = false; } GraphicsBase::~GraphicsBase(){ } void GraphicsBase::initialise(void){ if(!is_initialised){ initialiseSDL(); initialiseGL(); resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT); is_initialised = true; } } void GraphicsBase::resizeWindow(int width, int height){ if(height == 0){ height = 1; } float ratio = (float)width/(float)height; glViewport( 0, 0, width, height); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 45.0f, ratio, 0.1f, 1000.0f ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); } void GraphicsBase::test(void){ bool done = false; SDL_Event event; while(!done){ while (SDL_PollEvent(&event)){ switch( event.type ){ case SDL_VIDEORESIZE: resizeWindow( event.resize.w, event.resize.h ); break; case SDL_QUIT: done = true; default: break; } } testDraw(); } SDL_Quit(); } bool GraphicsBase::initialiseSDL(void){ int videoFlags; const SDL_VideoInfo *videoInfo; if(SDL_Init(SDL_INIT_VIDEO) < 0){ std::cerr << "Video initialisation failed: " << SDL_GetError() << std::endl; return false; } videoInfo = SDL_GetVideoInfo(); if(!videoInfo){ std::cerr << "Video query failed: " << SDL_GetError() << std::endl; return false; } videoFlags = SDL_OPENGL; videoFlags |= SDL_GL_DOUBLEBUFFER; videoFlags |= SDL_HWPALETTE; videoFlags |= SDL_RESIZABLE; if(videoInfo->hw_available){ videoFlags |= SDL_HWSURFACE; } else{ videoFlags |= SDL_SWSURFACE; } if(videoInfo->blit_hw){ videoFlags |= SDL_HWACCEL; } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); /* get a SDL surface */ surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 24, videoFlags ); if (!surface){ std::cerr << "Video mode set failed: " << SDL_GetError() << std::endl; return false; } return true; } bool GraphicsBase::initialiseGL(void){ glShadeModel( GL_SMOOTH ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClearDepth( 1.0f ); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); glHint( GL_POINT_SMOOTH_HINT, GL_NICEST ); glHint( GL_LINE_SMOOTH_HINT, GL_NICEST ); glPointSize(2.0f); return true; } void GraphicsBase::testDraw(void){ glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); /* Move Left 1.5 Units And Into The Screen 6.0 */ glLoadIdentity(); glTranslatef( -1.5f, 0.0f, -6.0f ); glBegin( GL_TRIANGLES ); /* Drawing Using Triangles */ glVertex3f( 0.0f, 1.0f, 0.0f ); /* Top */ glVertex3f( -1.0f, -1.0f, 0.0f ); /* Bottom Left */ glVertex3f( 1.0f, -1.0f, 0.0f ); /* Bottom Right */ glEnd( ); /* Finished Drawing The Triangle */ /* Move Right 3 Units */ glTranslatef( 3.0f, 0.0f, 0.0f ); glBegin( GL_QUADS ); /* Draw A Quad */ glVertex3f( -1.0f, 1.0f, 0.0f ); /* Top Left */ glVertex3f( 1.0f, 1.0f, 0.0f ); /* Top Right */ glVertex3f( 1.0f, -1.0f, 0.0f ); /* Bottom Right */ glVertex3f( -1.0f, -1.0f, 0.0f ); /* Bottom Left */ glEnd( ); /* Done Drawing The Quad */ /* Draw it to the screen */ SDL_GL_SwapBuffers( ); }
[ "osushkov@gmail.com" ]
osushkov@gmail.com
4f26ebc665fb9f99dbe94ee5d13f93c69a351adb
4144b8166e8563278d8144244da2dc16338a9d1d
/testing/sleeper/main.cpp
b2b5cd373d5b7e1fbb558eb0edc04414a47ac0f5
[ "Apache-2.0" ]
permissive
wikipedia2008/roofline
ed37815ca2bb453b112ac69f27ec37172cd4dfe8
ad6c63c021d82891b7ac159c4a0b97f25e59bbe3
refs/heads/master
2023-08-08T15:09:37.938010
2020-10-26T14:24:32
2020-10-26T14:24:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
#include<iostream> #include<chrono> #include<thread> int main(int argc, char* argv[]){ std::cout << "Hello, I'm feeling sleepy" << std::endl; std::cout << "Yahwn" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(5000)); std::cout << "I'm awake!" << std::endl; return 0; }
[ "agrant@arm.com" ]
agrant@arm.com
59325fc680c8e1a1b4226a21f2256e0742157896
6b59885c4a69f2d40f0148e9793636a45428f23b
/DungeonCrawler/Graphics/AnimatedEmitter.h
fbbad68289fd3905a15df3be231da0fc8234141a
[]
no_license
StevenCederrand/Dungeon-Crawler
cbc8e215e8e7756a9a931be47a7fa3203383dd9e
5340a5843d38356cb00064c5e2a5f1f246977b48
refs/heads/master
2022-01-08T17:23:20.429813
2019-05-28T11:47:50
2019-05-28T11:47:50
178,849,264
0
1
null
null
null
null
UTF-8
C++
false
false
2,469
h
#ifndef _ANIMATEDEMITTER_H #define _ANIMATEDEMITTER_H #include<GLM/glm.hpp> #include <vector> #include <Graphics/GLinit.h> #define MAX_PARTICLES 120 class GameObject; class AnimatedEmitter { public: AnimatedEmitter(GLinit* glInit, const std::string& spritesheet, unsigned pxWidth, unsigned pxHeight, unsigned frames, float animDelay, bool billboarded, float sizeOfAnParticle); ~AnimatedEmitter(); void update(float dt); void addParticle(const glm::vec3& pos, const glm::vec3& velocity, float lifetime, int numberOfParticles = 1); void addParticle(const glm::vec3& pos, const glm::vec3& rotation, const glm::vec3& velocity, float lifetime, int numberOfParticles = 1); void addParticle(GameObject* parent, const glm::vec3& offset, int numberOfParticles = 1); void addParticle(GameObject* parent, const glm::vec3& offset, const glm::vec3& rotation, int numberOfParticles = 1); const GLuint getVAO() const; const GLuint getTextureID() const; const unsigned int getNumberOfParticles() const; const unsigned int getNumberOfAnimationFrames() const; const bool isBillBoarded() const; private: struct Particle { glm::vec3 velocity; glm::vec3 center; glm::vec3 rotation; glm::vec3 offset; glm::vec4 color; float lifetime; float initialLifetime; int animState; float animTimer; glm::mat4 modelMatrix; bool immortal; GameObject* parent; bool hadParent; Particle() : center(0.0f), velocity(0.0f), rotation(0.0f), offset(0.0f), color(1.0f), lifetime(0.0f), initialLifetime(0.f), modelMatrix(1.0f), immortal(false), parent(nullptr), animState(0), animTimer(0.0f), hadParent(false) { } }; GLuint m_textureID = -1; unsigned int m_nrOfParticles = 0; unsigned int m_lastUnusedParticle = 0; std::vector<Particle> m_particles; std::vector<glm::vec3> m_centerPosBuffer; std::vector<glm::vec4> m_colorBuffer; std::vector<glm::mat4> m_modelMatrixBuffer; std::vector<float> m_animationIndices; GLuint m_vao; GLuint m_verticesVBO; GLuint m_uvVBO; GLuint m_centerVBO; GLuint m_colorVBO; GLuint m_animationStateVBO; GLuint m_modelMatrixVBO; GLfloat m_vertex_buffer_data[12]; GLfloat m_uv_buffer_data[8] = { 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; bool m_billboarded; // Animation props float m_animDelay; int m_pxWidth; int m_pxHeight; int m_frames; float m_indx = 0; private: void setupGraphicBuffers(); void updateBuffers(); size_t getFirstUnusedParticle(); }; #endif
[ "AlexanderAlsvold@hotmail.se" ]
AlexanderAlsvold@hotmail.se
4ed12bcce4175fb51cdf8366a1e3686cd76b138c
4a522703055877dc7e3df2db0507410d44c0f86b
/src/c/phonescope/gui.h
f516fd9bb53e19aa18f599afe427f0a1451be97d
[]
no_license
sbarman/PhoneSensor
ed98a6668e0d4f4af9c7604358328e7a0a0b14c2
657b2803f3a5ba1f37150f68ec6296eaa9202e12
refs/heads/master
2016-09-06T14:39:23.830086
2010-05-15T22:10:20
2010-05-15T22:10:20
596,459
1
0
null
null
null
null
UTF-8
C++
false
false
782
h
#ifndef GUI #define GUI #include <gtk/gtk.h> #include "scope.h" #include "datastream.h" // variables for drawing area class DrawingAreaVars { public: DrawingAreaVars(short *v, int vc, int ts, int as, int o); short* values; int values_count; int time_scale; int ampl_scale; int cur_position; int offset; pthread_mutex_t *mutex_read; pthread_mutex_t *mutex_write; }; class PhoneScopeGui { // widgets GtkWidget *box1; GtkWidget *notebook; GtkWidget *box2; GtkWidget *button; GtkWidget *separator; GtkWidget *table; GtkWidget *drawing_area; GtkWidget *box3; public: GtkWidget *window; GtkWidget *label; DataStream *datastream; alsa_shared *data; DrawingAreaVars *drawing_area_vars; PhoneScopeGui(alsa_shared *shared_data); void run(); }; #endif /* GUI */
[ "sbarman@eecs.berkeley.edu" ]
sbarman@eecs.berkeley.edu
7ebc2013c8ebc5c26504f8cd86a34106f4b7c2d2
c93f6ad566a66c0b16c9974b2cbfc44a27f713c4
/Rogy/Engine/shading/texture.h
877c2fc6e982782fadf4b8450dfa055b1843d774
[ "Apache-2.0" ]
permissive
Tekh-ops/Rogy-Engine-
3152ebb79b1a1a6270d46c3d130945ba16129f4a
fa85d501b813c6492046e15dce50521f817a244d
refs/heads/main
2023-07-19T19:09:55.707860
2021-09-05T20:55:47
2021-09-05T20:55:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,282
h
#ifndef TEXTURE_H #define TEXTURE_H #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> #include <GL\glew.h> class Texture { public: GLuint texID, texWidth, texHeight, texComponents; GLfloat anisoFilterLevel; GLenum texType, texInternalFormat, texFormat; std::string texName; std::string TPath; unsigned char* tData; int GetRed(int x, int y); int GetGreen(int x, int y); int GetBlue(int x, int y); int GetAlpha(int x, int y); Texture(); ~Texture(); bool setTexture(const char* texPath, std::string tex_Name, bool texFlip = false, bool keepData = false); void setTextureHDR(const char* texPath, std::string texName, bool texFlip); void setTextureHDR(GLuint width, GLuint height, GLenum format, GLenum internalFormat, GLenum type, GLenum minFilter); void setTextureCube(std::vector<const char*>& faces, bool texFlip); void setTextureCube(GLuint width, GLenum format, GLenum internalFormat, GLenum type, GLenum minFilter); void computeTexMipmap(); GLuint getTexID(); GLuint getTexWidth(); GLuint getTexHeight(); std::string getTexName(); std::string getTexPath(); void useTexture(); }; #endif
[ "43178999+FOLOME@users.noreply.github.com" ]
43178999+FOLOME@users.noreply.github.com
0ab01138e40a5c13ea6645c33d79d9b1eb4ec9c5
7b49d69735eee6602ce328cfcb719024446fe2bb
/exnerFoam/varianceTransfers/risingBubbleOneD/oneFluid/init_0/theta.stable
13be33ff399366bb4e04ac1a5f7b38cabe3f906c
[]
no_license
statisdisc/partitionedShallowWater
7ced6febdae948b222e18039ad622b5d7f0813a4
52422a24a9e3cdbe7c0f8f28c2e8d3f3e1257ca7
refs/heads/master
2021-06-22T16:33:21.060529
2020-08-21T08:39:11
2020-08-21T08:39:11
101,410,034
0
0
null
null
null
null
UTF-8
C++
false
false
13,259
stable
/*--------------------------------*- C++ -*----------------------------------*| ========= | | | \ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \ / O peration | Version: dev | | \ / A nd | Web: www.OpenFOAM.org | | \/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0"; object theta.stable; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 1 0 0 0]; internalField nonuniform List<scalar> 2000 ( 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 300.0 ) ; boundaryField { ground { type zeroGradient; } top { type zeroGradient; } left { type zeroGradient; } right { type zeroGradient; } defaultFaces { type empty; } } // ************************************************************************* //
[ "will.a.m@hotmail.co.uk" ]
will.a.m@hotmail.co.uk
fc5cfb9109051b933bbda44f0bed16a10dc5b8bb
7b46f4140b078c5cb7954b6735fff6a31e2e7751
/torch/csrc/api/include/torch/data/dataloader.h
006ca19e29a858770f4c8993551f501512ff5fea
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
jcjohnson/pytorch
f704a5a602f54f6074f6b49d1696f30e05dea429
ab253c2bf17747a396c12929eaee9d379bb116c4
refs/heads/master
2020-04-02T15:36:09.877841
2018-10-24T21:57:42
2018-10-24T22:02:40
101,438,891
8
2
NOASSERTION
2018-10-24T21:55:49
2017-08-25T20:13:19
Python
UTF-8
C++
false
false
10,027
h
#pragma once #include <torch/data/dataloader_options.h> #include <torch/data/detail/data_shuttle.h> #include <torch/data/detail/sequencers.h> #include <torch/data/iterator.h> #include <torch/data/samplers/random.h> #include <torch/data/worker_exception.h> #include <torch/tensor.h> #include <torch/csrc/utils/memory.h> #include <torch/csrc/utils/variadic.h> #include <c10/util/Exception.h> #include <c10/util/Optional.h> #include <cstddef> #include <exception> #include <memory> #include <thread> #include <type_traits> #include <utility> #include <vector> namespace torch { namespace data { template <typename Dataset, typename Sampler> class DataLoader { public: using Batch = typename Dataset::BatchType; using IndexBatch = std::vector<size_t>; /// Constructs a new `DataLoader` from a `dataset` to sample from, `options` /// to configure the `DataLoader` with, and a `sampler` that specifies the /// sampling strategy. DataLoader(Dataset dataset, DataLoaderOptions options, Sampler sampler) : options_(std::move(options)), sampler_(std::move(sampler)), sequencer_(new_sequencer()) { // clang-format off AT_CHECK( options_.batch_size <= dataset.size(), "Batch size (was ", options_.batch_size, ") ", "must not be larger than the dataset size (was ", dataset.size(), ")"); // clang-format on if (options_.workers > 0) { for (size_t w = 0; w < options_.workers; ++w) { // Here we copy the dataset into the worker thread closure. Each worker // has its own copy of the dataset. This means the dataset must be // trivially copiable, or else we don't expect more than one worker to // be in use. workers_.emplace_back( [this, dataset] { this->worker_thread(std::move(dataset)); }); } } else { main_thread_dataset_ = torch::make_unique<Dataset>(std::move(dataset)); } } ~DataLoader() { join(); } /// Returns an iterator into the `DataLoader`. The lifetime of the iterator is /// bound to the `DataLoader`. In C++ standards language, the category of the /// iterator is `OutputIterator`. See /// https://en.cppreference.com/w/cpp/named_req/OutputIterator for what this /// means. In short: you may increment the iterator and dereference it, but /// cannot go back, or step forward more than one position at a time. When the /// `DataLoader` is exhausted, it will compare equal with the special /// "sentinel" iterator returned by `DataLoader::end()`. Most of the time, you /// should only use range-for loops to loop over the `DataLoader`, but /// standard algorithms like `std::copy(dataloader.begin(), dataloader.end(), /// output_iterator)` are supported too. Iterator<Batch> begin() { AT_CHECK( shuttle_.in_flight_jobs() == 0, "Attempted to get a new DataLoader iterator " "while another iterator is not yet exhausted"); reset(); return Iterator<Batch>(torch::make_unique<detail::ValidIterator<Batch>>( [this] { return this->next(); })); } /// Returns a special "sentinel" iterator that compares equal with a /// non-sentinel iterator once the `DataLoader` is exhausted. Iterator<Batch> end() { return Iterator<Batch>( torch::make_unique<detail::SentinelIterator<Batch>>()); } /// Joins the `DataLoader`'s worker threads and drains internal queues. /// This function may only be invoked from the main thread (in which the /// `DataLoader` lives). void join() { if (joined_) { return; } shuttle_.drain(); // Send one 'quit' message per worker. Since a worker dies (exits its // thread) after receiving this message, each `QuitWorker()` message will be // read by exactly one worker. for (size_t w = 0; w < options_.workers; ++w) { push_job(QuitWorker()); } for (auto& worker : workers_) { worker.join(); } joined_ = true; } /// Returns the options with which the `DataLoader` was configured. const FullDataLoaderOptions& options() const noexcept { return options_; } private: /// Simple mix-in to give something a sequence number. struct Sequenced { Sequenced() = default; Sequenced(size_t sqn) : sequence_number(sqn) {} size_t sequence_number; }; struct QuitWorker {}; /// A `Job` is either an `IndexBatch` (new indices to fetch data at) or a /// `QuitWorker` object, to indicate the worker should shut down. struct Job : Sequenced { Job() = default; Job(QuitWorker q, size_t sqn) : Sequenced(sqn), quit(q) {} Job(IndexBatch&& i, size_t sqn) : Sequenced(sqn), index_batch(std::move(i)) {} optional<QuitWorker> quit; optional<IndexBatch> index_batch; }; /// The finished result of a job. struct Result : Sequenced { Result() = default; Result(Batch&& b, size_t sqn) : Sequenced(sqn), batch(std::move(b)) {} Result(std::exception_ptr exception, size_t sqn) : Sequenced(sqn), exception(std::move(exception)) {} optional<Batch> batch; std::exception_ptr exception; }; /// Resets the internal state of the `DataLoader`, optionally pre-fetching /// new jobs. void reset(bool prefetch = true) { shuttle_.drain(); sampler_.reset(); sequence_number_ = 0; sequencer_ = new_sequencer(); if (prefetch) { this->prefetch(); } } /// Schedules `requested_jobs` many new batches to be fetched. The actual /// number of jobs scheduled may be less if the `DataLoader` exhausts. void prefetch(size_t requested_jobs) { while (requested_jobs-- > 0) { if (auto index_batch = get_index_batch()) { push_job(std::move(*index_batch)); } else { break; } } } /// Schedules the maximum number of jobs (based on the `max_jobs` option). void prefetch() { prefetch(options_.max_jobs); } /// Returns the next batch of data, or an empty `optional` if the `DataLoader` /// is exhausted. This operation will block until a batch is available. optional<Batch> next() { optional<Batch> batch; if (options_.workers > 0) { optional<Result> result = sequencer_->next( [this] { return this->shuttle_.pop_result(this->options_.timeout); }); if (result) { if (result->exception) { throw WorkerException(result->exception); } else { AT_ASSERT(result->batch.has_value()); batch = std::move(result->batch); prefetch(1); } } } else if (auto index_batch = get_index_batch()) { AT_ASSERT(main_thread_dataset_ != nullptr); batch = main_thread_dataset_->get_batch(std::move(*index_batch)); } return batch; } /// The function that worker threads run. void worker_thread(Dataset dataset) { while (true) { auto job = shuttle_.pop_job(); if (job.quit) { break; } try { auto batch = dataset.get_batch(std::move(*job.index_batch)); shuttle_.push_result({std::move(batch), job.sequence_number}); } catch (...) { shuttle_.push_result({std::current_exception(), job.sequence_number}); } } } optional<IndexBatch> get_index_batch() { auto indices = sampler_.next(options_.batch_size); if (!indices || (indices->size() < options_.batch_size && options_.drop_last)) { return nullopt; } AT_ASSERT(!indices->empty()); return indices; } template <typename T> void push_job(T value) { shuttle_.push_job({std::move(value), sequence_number_++}); } std::unique_ptr<detail::sequencers::Sequencer<Result>> new_sequencer() { if (options_.enforce_ordering) { return torch::make_unique<detail::sequencers::OrderedSequencer<Result>>( options_.max_jobs); } return torch::make_unique<detail::sequencers::NoSequencer<Result>>(); } /// The options the `DataLoader` was configured with. const FullDataLoaderOptions options_; /// The dataset for the main thread, only has a value if the number of /// worker threads was configured as zero, meaning the main thread has to do /// all the work (synchronously). NOTE: Really want this to be on the heap /// when empty, therefore `unique_ptr` and not `optional`. std::unique_ptr<Dataset> main_thread_dataset_; /// The sampler with which new index batches are created. Sampler sampler_; /// The sequence number for the *next* batch to be retrieved from the /// dataset. size_t sequence_number_ = 0; /// The worker threads, running the `worker_thread()` method. std::vector<std::thread> workers_; /// The `DataShuttle` which takes care of the life cycle of a job. detail::DataShuttle<Job, Result> shuttle_; /// The `Sequencer`, which handles optional ordering of batches. std::unique_ptr<detail::sequencers::Sequencer<Result>> sequencer_; /// True if the `DataLoader` has joined its worker threads. bool joined_ = false; }; // namespace data /// Creates a new `DataLoader`, inferring the necessary template types from /// the given arguments. template <typename Dataset, typename Sampler> std::unique_ptr<DataLoader<Dataset, Sampler>> make_data_loader( Dataset dataset, DataLoaderOptions options, Sampler sampler) { return torch::make_unique<DataLoader<Dataset, Sampler>>( std::move(dataset), std::move(options), std::move(sampler)); } /// Creates a new `DataLoader`, inferring the necessary template types from /// the given arguments. template < typename Dataset, typename Sampler = samplers::RandomSampler, typename = torch::enable_if_t<std::is_constructible<Sampler, size_t>::value>> std::unique_ptr<DataLoader<Dataset, Sampler>> make_data_loader( Dataset dataset, DataLoaderOptions options = DataLoaderOptions()) { const auto size = dataset.size(); return torch::make_unique<DataLoader<Dataset, Sampler>>( std::move(dataset), std::move(options), Sampler(size)); } } // namespace data } // namespace torch
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
fd6acde6e055ad132d5c1432866b20a63ec3b78f
387a3b2d6b3e70d520d6cb4acf773469d743f88b
/estructuras.h
65721768ea2d26960848c23595cf93bd05b82f63
[]
no_license
mau-arrieta244/Proyecto_ED_BabiesFactory
1d92c5e152642b6b5e7ada3f8f07e9d25338077a
348473e1afa9ad5f49fed05aed68f6f167b49214
refs/heads/main
2023-05-05T17:55:23.271547
2021-05-05T04:23:02
2021-05-05T04:23:02
363,554,708
0
0
null
null
null
null
UTF-8
C++
false
false
2,289
h
#include <cstdlib> #include <iostream> #include <algorithm> #include <iostream> #include <ctime> #include <unistd.h> #include <Windows.h> #include <unistd.h> using namespace std; //Prototipos de estructuras struct Sentimiento; struct FabricaSentimiento; struct Nodo; struct Cola; // estructura nodo para lista simple struct Nodo{ Sentimiento * sentimiento; //TODO: CHANGE PRIORITY Nodo* siguiente; // puntero para enlazar nodos Nodo() { sentimiento = NULL; siguiente = NULL; } Nodo(Sentimiento * inSentimiento){ sentimiento = inSentimiento; // asigna los datos siguiente = NULL; } void imprimir(); }; struct Sentimiento{ string corazon; Sentimiento(string pCorazon){ corazon = pCorazon; } void imprimir(){ cout << "Corazon " << corazon << endl; } }; struct Cola{ Nodo *frente; Cola(){ frente = NULL; } // encabezados de funcion //void encolar (int dato); //Nodo* desencolar (void); Nodo* verFrente(void); void imprimir(void); void encolarSentimiento(Sentimiento * pSentimiento){ if (frente == NULL) frente = new Nodo(pSentimiento); else{ // referencia al primero para recorrer la lista Nodo* actual = frente; // recorre la lista hasta llegar al penultimo nodo while (actual->siguiente != NULL) actual = actual->siguiente; // Crea nuevo nodo, lo apunta con uN Nodo* nuevo = new Nodo(pSentimiento); //le quita el enlace al que era ultimo actual->siguiente = nuevo; } } }; struct FabricaSentimiento{ int capacidad; int sentimientosActivos; Cola * sentimientos; //ListaSimple * sentimientos; FabricaSentimiento(){ capacidad = 20; sentimientosActivos = 0; sentimientos = new Cola(); } /* void imprimir(){ sentimientos->imprimir(); } */ };
[ "gabrielfallas0803@gmail.com" ]
gabrielfallas0803@gmail.com
412fd8147284e74a34c54433df11af19a38e1913
7d58aebdb27071c04f7e26265bb12138b2583f2b
/src/csv2maropu.cpp
bcc1edbf1cb7bbdca69ad47c030ffc24c1de77fb
[ "Apache-2.0" ]
permissive
dcrankshaw/FastPFor
02053f3911ee901691c38b23de9d43c465ef10f4
8b536c5ff66fac919d49af46f6dfe906f65b85cf
refs/heads/master
2020-12-24T10:53:33.287125
2013-01-10T15:27:22
2013-01-10T15:27:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,648
cpp
/** * This is code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * * (c) Daniel Lemire, http://lemire.me/en/ */ #include "csv.h" #include "externalvector.h" #include "util.h" void print(externalvector &ev) { for (size_t i = 0; i < ev.size(); ++i) { vector < uint32_t > x = ev.get(i); for (size_t k = 0; k < x.size(); ++k) cout << x[k] << " "; cout << endl; } } int main(int argc, char **argv) { if (argc < 3) { cerr << " This will map a table (stored in a CSV file) to a row " " oriented flat file of frequency attributed 32-bit integers " << endl; cerr << " usage : cvs2maropu mycvsfile.cvs mymaropufile.bin " << endl; return -1; } string ifilename(argv[1]); string ofilename(argv[2]); CSVFlatFile cvs(ifilename.c_str(), CSVFlatFile::FREQNORMALISATION); const size_t c = cvs.getNumberOfColumns(); const size_t N = cvs.getNumberOfRows(); size_t integers = static_cast<uint32_t> (c * N); vector < uint32_t > container(c); FILE * fd = ::fopen(ofilename.c_str(), "w+b"); if (fd == NULL) { cout << " could not open " << ofilename << " for writing..." << endl; cvs.close(); return -1; } uint32_t MAXSIZE = c * (1U << 20); for (size_t block = 0; block * MAXSIZE >= integers; integers -= MAXSIZE) { if (fwrite(&MAXSIZE, sizeof(MAXSIZE), 1, fd) != 1) { cerr << "aborting" << endl; ::fclose(fd); cvs.close(); return -1; } uint32_t counter = 0; while (cvs.nextRow(container)) { if (fwrite(&container[0], c * sizeof(uint32_t), 1, fd) != 1) { cerr << "aborting" << endl; ::fclose(fd); cvs.close(); return -1; } counter += c; if (counter == block) break; assert(counter < block); } } if (integers > 0) { uint32_t tsize = integers; if (fwrite(&tsize, sizeof(tsize), 1, fd) != 1) { cerr << "aborting" << endl; ::fclose(fd); cvs.close(); return -1; } while (cvs.nextRow(container)) { if (fwrite(&container[0], c * sizeof(uint32_t), 1, fd) != 1) { cerr << "aborting" << endl; ::fclose(fd); cvs.close(); return -1; } } } ::fclose(fd); cvs.close(); cout << "#file " << ofilename << " contains your data." << endl; }
[ "lemire@gmail.com" ]
lemire@gmail.com
fcc9f5d31b82739262401e4e0416901b5c031aca
99293a5098087565587e5b6904c240837f1aa33a
/17-7-22/b.cpp
013c45c2d6dc3e37c72b51e367f16a25fbbe283a
[]
no_license
3013216006/ACM
1a97b571a0d464c27733ed6660438e55c7085d6a
bd37587e9a079a0ade0c6fc29b8d522eb39f8973
refs/heads/master
2020-05-21T14:32:43.810301
2017-08-24T13:23:03
2017-08-24T13:23:03
84,624,689
0
0
null
null
null
null
UTF-8
C++
false
false
1,884
cpp
#include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> using namespace std; struct Node{ long long x,y; }a[3],b[3]; long long xmul(Node a,Node b,Node c){ return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y); } long long myabs(long long x){ if(x<0) return -x; return x; } void swap(){ for(int i=0;i<3;i++){ swap(a[i].x,b[i].x); swap(a[i].y,b[i].y); } } int pan(int x){ int ret=1; for(int i=0;i<3;i++){ int a1=(i+1)%3; int a2=(i+2)%3; long long tmp=xmul(a[i],a[a1],a[a2])*xmul(b[x],a[a1],a[a2]); if(tmp==0) ret=0; if(tmp<0) return -1; } return ret; } int _is(Node a,Node b,Node c,Node d){ long long x1=xmul(c,a,b)*xmul(d,a,b); long long x2=xmul(a,c,d)*xmul(b,c,d); //if(xmul(c,a,b)*xmul(d,a,b)>0) return 0; //if(xmul(a,c,d)*xmul(b,c,d)>0) return 0; if(x1>0) return 0; if(x2>0) return 0; // if(x1==0&&x2==0) return 0; return 1; } int main(){ int T; scanf("%d",&T); while(T--){ for(int i=0;i<3;i++) scanf("%I64d%I64d",&a[i].x,&a[i].y); for(int i=0;i<3;i++) scanf("%I64d%I64d",&b[i].x,&b[i].y); long long s1=myabs(xmul(a[0],a[1],a[2])); long long s2=myabs(xmul(b[0],b[1],b[2])); if(s1<s2) swap(); int ans=0,ans1=0; for(int i=0;i<3;i++){ long long x=pan(i); if(x>0) ans++; if(x==0) ans1++; } swap(); int ans2=0,ans3=0; for(int i=0;i<3;i++){ long long x=pan(i); // if(x>=0) ans2++; if(x==0) ans1++; } /* if(ans==3){ if(ans-ans1!=3) puts("intersect"); else puts("contain"); } else if(ans2){ if(ans2-ans3!=3) puts("intersect"); else puts("contain"); } // if(ans==3&&ans1==0) // puts("contain"); */ if(ans==3){ puts("contain"); } else{ int flag=0; for(int i=0;i<3;i++) for(int j=0;j<3;j++){ if(_is(a[i],a[(i+1)%3],b[j],b[(j+1)%3])) flag=1; } if(ans1) flag=1; if(flag) puts("intersect"); else puts("disjoint"); } } }
[ "fuxuzhoude@126.com" ]
fuxuzhoude@126.com
323b01474beb3d0d0c0e8026f9f44b077d22130e
b85ef32050f35569f89678b9a93fb95a4f1fc30d
/common/protobuf2.5.0/PROTOBUF-2.5.0RC1/src/google/protobuf/compiler/cpp/cpp_enum.h
c04669b591ca266b8af963a0c0c4da6d15816753
[ "LicenseRef-scancode-protobuf" ]
permissive
zjutjsj1004/star
46e4d7d9dc6fe695aabc258e134172e64e6003a6
2ed3401841da816d081446c52697fc9a40a799c6
refs/heads/master
2021-01-10T01:50:40.981295
2016-01-11T05:43:32
2016-01-11T05:43:32
45,163,605
2
0
null
null
null
null
UTF-8
C++
false
false
3,828
h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__ #define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__ #include <string> #include <google/protobuf/compiler/cpp/cpp_options.h> #include <google/protobuf/descriptor.h> namespace google { namespace protobuf { namespace io { class Printer; // printer.h } } namespace protobuf { namespace compiler { namespace cpp { class EnumGenerator { public: // See generator.cc for the meaning of dllexport_decl. explicit EnumGenerator(const EnumDescriptor* descriptor, const Options& options); ~EnumGenerator(); // Header stuff. // Generate header code defining the enum. This code should be placed // within the enum's package namespace, but NOT within any class, even for // nested enums. void GenerateDefinition(io::Printer* printer); // Generate specialization of GetEnumDescriptor<MyEnum>(). // Precondition: in ::google::protobuf namespace. void GenerateGetEnumDescriptorSpecializations(io::Printer* printer); // For enums nested within a message, generate code to import all the enum's // symbols (e.g. the enum type name, all its values, etc.) into the class's // namespace. This should be placed inside the class definition in the // header. void GenerateSymbolImports(io::Printer* printer); // Source file stuff. // Generate code that initializes the global variable storing the enum's // descriptor. void GenerateDescriptorInitializer(io::Printer* printer, int index); // Generate non-inline methods related to the enum, such as IsValidValue(). // Goes in the .cc file. void GenerateMethods(io::Printer* printer); private: const EnumDescriptor* descriptor_; string classname_; Options options_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); }; } // namespace cpp } // namespace compiler } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
[ "18767122273@163.com" ]
18767122273@163.com
94d7607e67093d1c122048468c25fb1452e20a84
5902fa0857cd4f722a9663bbd61aa0895b9f8dea
/BMIG-5101-SequencesAsBioInformation/Blast/ncbi-blast-2.10.0+-src/c++/include/util/range_coll.hpp
605da6d159abbca972f23d50f7da26e9280b849a
[]
no_license
thegrapesofwrath/spring-2020
1b38d45fa44fcdc78dcecfb3b221107b97ceff9c
f90fcde64d83c04e55f9b421d20f274427cbe1c8
refs/heads/main
2023-01-23T13:35:05.394076
2020-12-08T21:40:42
2020-12-08T21:40:42
319,763,280
0
0
null
null
null
null
UTF-8
C++
false
false
130
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:0a2ea745aaf9cc0ea44343db5fc91ef57af30c458ff000d9d60a5d2f6e7c8e27 size 13854
[ "shawn-hartley@sbcglobal.net" ]
shawn-hartley@sbcglobal.net
1ef5a762746f5c549615a777b9525d1295bf3259
fb49ea78ff9dab6bcb2ecf5ffd55392e040d804a
/VECTOR2.h
8878f3d4c50c32990c794286442748c859e07a68
[]
no_license
senrixMOMO/tetris
e8a6993831e1d03efd430b07841a55b207b12e35
aa2cd26dcc5070253ffc890d81f2628155c3aa9f
refs/heads/master
2020-05-20T02:34:23.382448
2019-05-07T06:33:14
2019-05-07T06:33:14
185,335,890
0
0
null
null
null
null
ISO-8859-7
C++
false
false
968
h
#pragma once class VECTOR2 { public: VECTOR2(); VECTOR2(int x, int y); ~VECTOR2(); int x; int y; //‘γ“ό‰‰ŽZŽq VECTOR2& operator = (const VECTOR2& vec); //“Y‚¦Žš‰‰ŽZŽq int& operator[](int i); //”δŠr‰‰ŽZŽq bool operator==(const VECTOR2& vec) const; bool operator!=(const VECTOR2& vec) const; //’P€‰‰ŽZŽq VECTOR2& operator += (const VECTOR2& vec); VECTOR2& operator -= (const VECTOR2& vec); VECTOR2& operator *= (int k); VECTOR2& operator /= (int k); VECTOR2 operator +() const; VECTOR2 operator -() const; }; //ΝήΈΔΩ‚Μ‰‰ŽZ //VECTOR2 + VECTOR2 VECTOR2 operator+(const VECTOR2& u, const VECTOR2& v); //VECTOR2 - VECTOR2 VECTOR2 operator-(const VECTOR2& u, const VECTOR2& v); //int * VECTOR2 VECTOR2 operator*(int k, const VECTOR2& v); //Vector3D * int VECTOR2 operator*(const VECTOR2& v, int k); //Vector3D / int VECTOR2 operator/(const VECTOR2& v, int k); VECTOR2 operator%(const VECTOR2& v, int k);
[ "senri990102@icloud.com" ]
senri990102@icloud.com
d4ec3d7d4bb7923a1ca802555e69ffc94a84ae3c
dd0c733f8da13fc34303e3a8fba7f1811bbca4c4
/P10-1-3.cpp
157083ca9afcfe735ba96c7327130576e3970891
[]
no_license
byh1321/CppExamplesandProblems
e43706e55e43935f9e4237775ff509a6410090a8
fe98f81f545101a41d8402ea07390924293c1caa
refs/heads/master
2021-01-11T08:23:45.294541
2016-12-18T07:27:06
2016-12-18T07:27:06
76,769,036
0
1
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include<iostream> using namespace std; class Point { private: int xpos, ypos; public: Point(int x = 0, int y = 0) : xpos(x), ypos(y) { //empty } void ShowPosition() const { cout << '[' << xpos << "," << ypos << ']' << endl; } friend bool operator==(const Point &ref1, const Point &ref2) { if (ref1.xpos == ref2.xpos && ref1.ypos == ref2.ypos) return true; else return false; } friend bool operator!=(const Point &ref1,const Point &ref2) { return !(ref1 == ref2); } }; void main() { Point pos1(3, 4); Point pos2(10, 20); Point pos3(3, 4); cout << (pos1 == pos2) << endl; cout << (pos1 == pos3) << endl; }
[ "byh1321@naver.com" ]
byh1321@naver.com
847fcc6409999ff283d1d8e9e4a2a796b2dd2de4
1259dcae8bcadf78d30d83976860510dd407502d
/lib/utils/macros.hpp
cdba4cb91b01867c657855a55bd502b4fcd476be
[ "MIT" ]
permissive
ccrisrober/monkeybrushplusplus
de83c6fc7719d9adb8cf42867da15560462c0b3f
2bccca097402ff1f5344e356f06de19c8c70065b
refs/heads/master
2021-06-13T23:15:59.424708
2017-02-11T13:06:26
2017-02-11T13:06:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,008
hpp
/* * Copyright (c) 2016 maldicion069 * * Authors: Cristian Rodríguez Bernal <ccrisrober@gmail.com> * * This file is part of MonkeyBrushPlusPlus * <https://github.com/maldicion069/monkeybrushplusplus> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3.0 as published * by the Free Software Foundation. * * This library 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 this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef __MB__MACROS__ #define __MB__MACROS__ // Create automatic getter and setter. #define MB_SYNTHESIZE(varType, varName, funName)\ protected: varType varName;\ public: virtual varType get##funName(void) const { return varName; }\ public: virtual void set##funName(varType var){ varName = var; } // Create automatic setter. #define MB_SYNTHESIZE_WRITEONLY(varType, varName, funName)\ protected: varType varName;\ public: virtual void set##funName(varType var){ varName = var; } // Create automatic getter and setter with pass by reference. #define MB_SYNTHESIZE_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ public: virtual const varType& get##funName(void) const { return varName; }\ public: virtual void set##funName(const varType& var){ varName = var; } // Create automatic setter with pass by reference. #define MB_SYNTHESIZE_WRITEONLY_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ public: virtual void set##funName(const varType& var){ varName = var; } // Create automatic getter for readonly. #define MB_SYNTHESIZE_READONLY(varType, varName, funName)\ protected: varType varName;\ public: virtual varType get##funName(void) const { return varName; }\ // Create only getter header method. #define MB_PROPERTY_READONLY(varType, varName, funName)\ protected: varType varName;\ public: virtual varType get##funName(void) const; // Create only getter header method with pass by reference. #define MB_PROPERTY_READONLY_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ public: virtual const varType& get##funName(void) const; // Create only getter and setter header. #define MB_PROPERTY(varType, varName, funName)\ protected: varType varName;\ public: virtual varType get##funName(void) const;\ public: virtual void set##funName(varType var); // Create only getter and setter header with pass by reference. #define MB_PROPERTY_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ public: virtual const varType& get##funName(void) const;\ public: virtual void set##funName(const varType& var); #endif /* __MB__MACROS__ */
[ "ccrisrober@gmail.com" ]
ccrisrober@gmail.com
0e50c5f197c88f75546102c937fae1f712031c08
4f32a78f56dd0bb9a16239782ed28074a2ff66ec
/Algorithmic Toolbox/Week2/01_introduction_starter_files/fibonacci/Solution/fibonacci.cpp
9b1c3237eb3b902869c983fbc48e01613d1512a9
[]
no_license
drumilmahajan/Data-Structures-and-Algorithms---Coursera
98d2151c1ff67404270d8e28bf411fcef3e5cce4
7c11f16e1c4b03dc6a1dfc8aeef11d042705c9fb
refs/heads/master
2020-05-29T08:47:58.561716
2016-11-18T18:34:20
2016-11-18T18:34:20
70,198,169
0
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
#include <iostream> long calc_fib(int n) { long a=0; long b=1; long c =0; if(n==0) return 0; if(n==1) return 1; else{ for(int i = 2 ; i<=n ; i++) { c=a+b; a=b; b=c; } return c; } } int main() { int n = 0; std::cin >> n; std::cout << calc_fib(n) << '\n'; return 0; }
[ "dm3804@nyu.edu" ]
dm3804@nyu.edu
da157ade55b1853be0ef5a9d057a82edafb36b48
c45aec0456060e4bec9dafaee1146535112ccc18
/twochannelaltimeter.h
bf3a8ec6eb2b80d585d076fc77af3955d4c9fc0f
[]
no_license
henrich14/RadioAltimeter
16fc70b03a839e6a605b4c61445701abede2ea3c
ee7a0bfd387978d5a1dd43fdbfa9c693e4103c77
refs/heads/master
2016-08-11T00:39:33.365126
2016-01-07T16:01:39
2016-01-07T16:01:39
49,213,907
0
0
null
null
null
null
UTF-8
C++
false
false
871
h
#ifndef TWOCHANNELALTIMETER_H #define TWOCHANNELALTIMETER_H #include <QWidget> #include <QtCore> #include <QtGui> #include <qwt_plot.h> #include <qwt_plot_canvas.h> #include <qwt_plot_curve.h> #include <qwt_legend.h> #include <qwt_plot_grid.h> #include <muParser.h> namespace Ui { class TwoChannelAltimeter; } class TwoChannelAltimeter : public QWidget { Q_OBJECT public: explicit TwoChannelAltimeter(QWidget *parent = 0); ~TwoChannelAltimeter(); private: Ui::TwoChannelAltimeter *ui; QwtPlotCurve *firstChannel; QwtPlotCurve *secondChannel; QwtPlotCurve *firstChannel_2; QwtPlotCurve *secondChannel_2; QwtPlotGrid *grid; QwtPlotGrid *grid2; QwtPlotGrid *grid3; QwtLegend *legend; QwtLegend *legend2; QwtLegend *legend3; private slots: void drawDiffFreq(); }; #endif // TWOCHANNELALTIMETER_H
[ "h.glaseropitz@gmail.com" ]
h.glaseropitz@gmail.com
2d8ef011a9b1f685b88d9fa70cb9f924668622c7
01de657b2ff7f2d37806c58299e3356ee140545a
/src/material/material.cpp
34e53b13c5286e558f1cd1b4031c0c39ab168daa
[]
no_license
Throbbing/lsrender
75bb26b74917bf9bd860da709c5b34ab1af8d9c0
03f58652be97abba0f947064bace00a70c48a4f9
refs/heads/master
2020-04-04T00:15:37.082032
2020-01-18T08:06:53
2020-01-18T08:06:53
155,646,511
4
1
null
null
null
null
UTF-8
C++
false
false
725
cpp
#include<material/material.h> #include<record/record.h> #include<spectrum/spectrum.h> #include<scatter/scatter.h> ls::Spectrum ls::Material::scatteringFactor(ls_Param_In const ScatteringRecord & sr, ls_Param_In const IntersectionRecord & ir) { if (sr.scatterFlag & EScattering_Reflection) return reflectance(ir); else return transmittance(ir); } ls::DummyMaterial::DummyMaterial() { mDummyScatter = new DummyScatter(); } ls::DummyMaterial::~DummyMaterial() { delete mDummyScatter; } ls::Spectrum ls::DummyMaterial::reflectance(ls_Param_In const IntersectionRecord & ir) { return Spectrum(1.f); } ls::Spectrum ls::DummyMaterial::transmittance(ls_Param_In const IntersectionRecord & ir) { return Spectrum(1.f); }
[ "1015640199@qq.com" ]
1015640199@qq.com
804f4e07624e8aaed38bef5898ee12363516dcf5
c54a93c3356de22f32bf5c6e92f051391046734a
/platform_release/windows/adobe/future/widgets/headers/platform_optional_panel.hpp
74955c1996ebf452aaa3e9cd313aaf1281b46021
[]
no_license
tfiner/adobe_asl
8d2eb6ae715b29217e411001b946914ff23b5f59
d7d1c2af5e0cf15fa8a170bb8d725dc935796c8a
refs/heads/master
2020-12-24T15:49:13.250941
2012-07-23T05:49:27
2012-07-23T05:49:27
4,744,424
1
0
null
null
null
null
UTF-8
C++
false
false
2,274
hpp
/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /****************************************************************************************************/ #ifndef ADOBE_WIDGET_OPTIONAL_PANEL_HPP #define ADOBE_WIDGET_OPTIONAL_PANEL_HPP /****************************************************************************************************/ #include <adobe/config.hpp> #include <adobe/any_regular.hpp> #include <adobe/extents.hpp> #include <adobe/layout_attributes.hpp> #include <adobe/widget_attributes.hpp> #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <adobe/future/widgets/headers/platform_panel.hpp> /****************************************************************************************************/ namespace adobe { /****************************************************************************************************/ struct optional_panel_t : boost::noncopyable { typedef any_regular_t model_type; typedef boost::function<void (const boost::function<void ()>&)> optional_display_proc_t; optional_panel_t(const any_regular_t& show_value, theme_t theme); void measure(extents_t& result); void place(const place_data_t& place_data); void display(const any_regular_t& value); void set_optional_display_procs(const optional_display_proc_t& show_proc, const optional_display_proc_t& hide_proc) { show_proc_m = show_proc; hide_proc_m = hide_proc; } panel_t control_m; optional_display_proc_t show_proc_m; optional_display_proc_t hide_proc_m; bool inited_m; }; /****************************************************************************************************/ } // namespace adobe /****************************************************************************************************/ #endif /****************************************************************************************************/
[ "github@tfiner.fastmail.fm" ]
github@tfiner.fastmail.fm
ee838ba76c28d9c85197a4154cacbf3120c0a86f
a2111a80faf35749d74a533e123d9da9da108214
/raw/pmsb13/pmsb13-data-20130530/sources/21gbd4mgnulhm130/2013-04-12T09-24-52.259+0200/sandbox/olfrik/apps/t5Graphs/t5Graphs.cpp
66e24a6c8145c683aeb59c3add70a39b25229289
[ "MIT" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
UTF-8
C++
false
false
6,168
cpp
// ========================================================================== // t5Graphs // ========================================================================== // Copyright (c) 2006-2012, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: Your Name <your.email@example.net> // ========================================================================== #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/arg_parse.h> // ========================================================================== // Classes // ========================================================================== // -------------------------------------------------------------------------- // Class AppOptions // -------------------------------------------------------------------------- // This struct stores the options from the command line. // // You might want to rename this to reflect the name of your app. struct AppOptions { // Verbosity level. 0 -- quiet, 1 -- normal, 2 -- verbose, 3 -- very verbose. int verbosity; // The first (and only) argument of the program is stored here. seqan::CharString text; AppOptions() : verbosity(1) {} }; // ========================================================================== // Functions // ========================================================================== // -------------------------------------------------------------------------- // Function parseCommandLine() // -------------------------------------------------------------------------- seqan::ArgumentParser::ParseResult parseCommandLine(AppOptions & options, int argc, char const ** argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("t5Graphs"); // Set short description, version, and date. setShortDescription(parser, "Put a Short Description Here"); setVersion(parser, "0.1"); setDate(parser, "July 2012"); // Define usage line and long description. addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fITEXT\\fP\""); addDescription(parser, "This is the application skelleton and you should modify this string."); // We require one argument. addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::STRING, "TEXT")); addOption(parser, seqan::ArgParseOption("q", "quiet", "Set verbosity to a minimum.")); addOption(parser, seqan::ArgParseOption("v", "verbose", "Enable verbose output.")); addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Enable very verbose output.")); // Add Examples Section. addTextSection(parser, "Examples"); addListItem(parser, "\\fBt5Graphs\\fP \\fB-v\\fP \\fItext\\fP", "Call with \\fITEXT\\fP set to \"text\" with verbose output."); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Only extract options if the program will continue after parseCommandLine() if (res != seqan::ArgumentParser::PARSE_OK) return res; // Extract option values. if (isSet(parser, "quiet")) options.verbosity = 0; if (isSet(parser, "verbose")) options.verbosity = 2; if (isSet(parser, "very-verbose")) options.verbosity = 3; seqan::getArgumentValue(options.text, parser, 0); return seqan::ArgumentParser::PARSE_OK; } // -------------------------------------------------------------------------- // Function main() // -------------------------------------------------------------------------- // Program entry point. int main(int argc, char const ** argv) { // Parse the command line. seqan::ArgumentParser parser; AppOptions options; seqan::ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv); // If there was an error parsing or built-in argument parser functionality // was triggered then we exit the program. The return code is 1 if there // were errors and 0 if there were none. if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; std::cout << "EXAMPLE PROGRAM\n" << "===============\n\n"; // Print the command line arguments back to the user. if (options.verbosity > 0) { std::cout << "__OPTIONS____________________________________________________________________\n" << '\n' << "VERBOSITY\t" << options.verbosity << '\n' << "TEXT \t" << options.text << "\n\n"; } return 0; }
[ "mail@bkahlert.com" ]
mail@bkahlert.com
09d0828feff1fa348b9937c79cc3956a283aa5d0
57918b8f0558a69f93b28612f7cb1c8851ad90a3
/diablo/Events.h
f456f2bc0ce9c79d335a58042924ecf51b625dfe
[]
no_license
brucelevis/diabloraid
db6cf0ad41bbd7189ef9f2a6bb109f710ac0aff9
bcf2f08818a8e63eeff29b747e38e01f03d72635
refs/heads/master
2021-01-02T09:34:12.926381
2013-11-30T10:21:39
2013-11-30T10:21:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
476
h
// // Events.h // diablo // // Created by Kosuke Takami on 2013/09/30. // // #ifndef __diablo__Events__ #define __diablo__Events__ #include <iostream> #include "cocos2d.h" #include "EventBase.h" using namespace cocos2d; class EventBase; class Events : public CCArray{ bool _handling; public: static CCArray* create(); void handle(CCLayer* layer); void setHandling(bool handling); Events(); ~Events(); }; #endif /* defined(__diablo__Events__) */
[ "takami.kosuke@dena.com" ]
takami.kosuke@dena.com
aabbd6eeed16c6a1e97723157ac160942ff6d4a6
8c1068ceb38f9d26c95bf9d797d80280322a106b
/coding.cpp
de26fab3dd498c3150b04a38cb4906a05c74d9fa
[ "MIT" ]
permissive
ardacihaner/huffman_coder
4ae3b651d69f79a9634fa12de16688f12173be52
dd04a4591a27dba326d2fd4a9bce61a5ebf5ba16
refs/heads/master
2023-03-14T09:04:50.574756
2021-03-06T18:21:21
2021-03-06T18:21:21
345,160,026
0
0
null
null
null
null
UTF-8
C++
false
false
1,124
cpp
#include <iostream> #include "binary_tree.cpp" using std::string; /** * decode() function takes two arguments, the first one is the encoding tree that is going to be used * The second one is the encoded data. */ string decode(BinaryTree &tree, string input_string) { string ret_str = ""; treeNode *const rootNode = tree.rootNode; treeNode *node = rootNode; for (char c : input_string) { if (node->left == nullptr && node->right == nullptr) { ret_str += node->data.data; node = rootNode; } if (c == '0') node = node->left; if (c == '1') node = node->right; } ret_str += node->data.data; return ret_str; } /** * encode() function takes two arguments, the first one is the encoding tree that is going to be used * The second one is the strint to be encoded */ string encode(BinaryTree &tree, string input_data) { string ret_string = ""; map<char, string> charMap = tree.getCharMap(); for (char c : input_data) { ret_string += charMap.at(c); } return ret_string; }
[ "arda.cihaner@gmail.com" ]
arda.cihaner@gmail.com
8d9263202c75b84738f5f73fd2df9f7741fb551c
4a36e8a7f598bb910a1cef0732702828106d98ca
/Dragon/modules/python/py_operator.h
e5c3195de52c9db970f06e9b41f64527fef10548
[ "BSD-2-Clause" ]
permissive
awesome-archive/Dragon
d5a5e737d63f71ba8b73306051aa9960d48e7447
b35f9320909d07d138c2f6b345a4c24911f7c521
refs/heads/master
2023-08-21T09:07:58.238769
2019-03-20T09:01:37
2019-03-20T09:01:37
177,972,970
0
0
BSD-2-Clause
2020-01-13T03:40:54
2019-03-27T10:41:13
C++
UTF-8
C++
false
false
1,764
h
/*! * Copyright (c) 2017-present, SeetaTech, Co.,Ltd. * * Licensed under the BSD 2-Clause License. * You should have received a copy of the BSD 2-Clause License * along with the software. If not, See, * * <https://opensource.org/licenses/BSD-2-Clause> * * ------------------------------------------------------------ */ #ifndef DRAGON_PYTHON_PY_OPERATOR_H_ #define DRAGON_PYTHON_PY_OPERATOR_H_ #include "py_dragon.h" namespace dragon { namespace python { void AddOperatorMethods(pybind11::module& m) { /*! \brief Return all the registered operators */ m.def("RegisteredOperators", []() { return CPUOperatorRegistry()->keys(); }); /*! \brief Return all the operators without gradients */ m.def("NoGradientOperators", []() { return NoGradientRegistry()->keys(); }); /*! \brief Run a operator from the def reference */ m.def("RunOperator", []( OperatorDef* def, const bool verbose) { pybind11::gil_scoped_release g; if (verbose) { // It is not a good design to print the debug string std::cout << def->DebugString() << std::endl; } ws()->RunOperator(*def); }); /*! \brief Run a operator from the serialized def */ m.def("RunOperator", []( const string& serialized, const bool verbose) { OperatorDef def; CHECK(def.ParseFromString(serialized)); pybind11::gil_scoped_release g; if (verbose) { // It is not a good design to print the debug string std::cout << def.DebugString() << std::endl; } ws()->RunOperatorOnce(def); }); } } // namespace python } // namespace dragon #endif // DRAGON_PYTHON_PY_OPERATOR_H_
[ "ting.pan@seetatech.com" ]
ting.pan@seetatech.com
4176bd5beeef374bc125f457110b6beec9e1d666
2a789b765c29f1b4fbf7197356317c4704c9a4b7
/arduino/Marlin_main.cpp
8cd4acc2eef5c321406baa0e6d3191c8e6c404f1
[]
no_license
zhou-peter/Q4maker
968ed50abe3a1beeb305125e4d933a34cbc349db
f5cd7ba038a7c3085c801d2e704309ceebff24ee
refs/heads/master
2022-02-14T14:49:56.137497
2019-07-29T10:24:58
2019-07-29T10:24:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
277,024
cpp
/** * Marlin 3D Printer Firmware * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] */ #include "Marlin.h" #include "ultralcd.h" //display #include "planner.h" #include "stepper.h" #include "endstops.h" #include "temperature.h" #include "cardreader.h" #include "configuration_store.h" #include "language.h" #include "pins_arduino.h" #include "math.h" #include "nozzle.h" #include "duration_t.h" #include "types.h" #if ENABLED(MESH_BED_LEVELING) #include "mesh_bed_leveling.h" #endif #if ENABLED(BEZIER_CURVE_SUPPORT) #include "planner_bezier.h" #endif #if ENABLED(USE_WATCHDOG) #include "watchdog.h" #endif #if HAS_SERVOS #include "servo.h" #endif #if HAS_DIGIPOTSS #include <SPI.h> #endif #if ENABLED(EXPERIMENTAL_I2CBUS) #include "twibus.h" #endif #if ENABLED(M100_FREE_MEMORY_WATCHER) void gcode_M100(); #endif #if ENABLED(SDSUPPORT) CardReader card; #endif #if ENABLED(EXPERIMENTAL_I2CBUS) TWIBus i2c; #endif /** * ----------------- * Implemented Codes * ----------------- * * "G" Codes * * G0 -> G1 * G1 - Coordinated Movement X Y Z E * G2 - CW ARC * G3 - CCW ARC * G4 - Dwell S<seconds> or P<milliseconds> * G5 - Cubic B-spline with XYZE destination and IJPQ offsets * G10 - Retract filament according to settings of M207 * G11 - Retract recover filament according to settings of M208 * G12 - Clean tool * G20 - Set input units to inches * G21 - Set input units to millimeters * G28 - Home one or more axes * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet. * G30 - Single Z probe, probes bed at current XY location. * G31 - Dock sled (Z_PROBE_SLED only) * G32 - Undock sled (Z_PROBE_SLED only) * G90 - Use Absolute Coordinates * G91 - Use Relative Coordinates * G92 - Set current position to coordinates given * * "M" Codes * * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled) * M1 - Same as M0 * M17 - Enable/Power all stepper motors * M18 - Disable all stepper motors; same as M84 * M20 - List SD card * M21 - Init SD card * M22 - Release SD card * M23 - Select SD file (M23 filename.g) * M24 - Start/resume SD print * M25 - Pause SD print * M26 - Set SD position in bytes (M26 S12345) * M27 - Report SD print status * M28 - Start SD write (M28 filename.g) * M29 - Stop SD write * M30 - Delete file from SD (M30 filename.g) * M31 - Output time since last M109 or SD card start to serial * M32 - Select file and start SD print (Can be used _while_ printing from SD card files): * syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#" * Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include). * The '#' is necessary when calling from within sd files, as it stops buffer prereading * M33 - Get the longname version of a path * M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used. * M48 - Measure Z_Probe repeatability. M48 [P # of points] [X position] [Y position] [V_erboseness #] [E_ngage Probe] [L # of legs of travel] * M75 - Start the print job timer * M76 - Pause the print job timer * M77 - Stop the print job timer * M78 - Show statistical information about the print jobs * M80 - Turn on Power Supply * M81 - Turn off Power Supply * M82 - Set E codes absolute (default) * M83 - Set E codes relative while in Absolute Coordinates (G90) mode * M84 - Disable steppers until next move, * or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default) * M92 - Set planner.axis_steps_per_mm - same syntax as G92 * M104 - Set extruder target temp * M105 - Read current temp * M106 - Fan on * M107 - Fan off * M108 - Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling * IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F * M110 - Set the current line number * M111 - Set debug flags with S<mask>. See flag bits defined in enum.h. * M112 - Emergency stop * M113 - Get or set the timeout interval for Host Keepalive "busy" messages * M114 - Output current position to serial port * M115 - Capabilities string * M117 - Display a message on the controller screen * M119 - Output Endstop status to serial port * M120 - Enable endstop detection * M121 - Disable endstop detection * M126 - Solenoid Air Valve Open (BariCUDA support by jmil) * M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil) * M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil) * M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil) * M140 - Set bed target temp * M145 - Set the heatup state H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS) * M149 - Set temperature units * M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work. * M163 - Set a single proportion for a mixing extruder. Requires MIXING_EXTRUDER. * M164 - Save the mix as a virtual extruder. Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. Requires MIXING_EXTRUDER. * M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.) * M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000) * M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!! * M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec * M204 - Set default acceleration: P for Printing moves, R for Retract only (no X, Y, Z) moves and T for Travel (non printing) moves (ex. M204 P800 T3000 R9000) in units/sec^2 * M205 - Set advanced settings. Current units apply: S<print> T<travel> minimum speeds B<minimum segment time> X<max xy jerk>, Z<max Z jerk>, E<max E jerk> * M206 - Set additional homing offset * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance> * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min> * M209 - Turn Automatic Retract Detection on/off: S<bool> (For slicers that don't support G10/11). Every normal extrude-only move will be classified as retract depending on the direction. * M218 - Set a tool offset: T<index> X<offset> Y<offset> * M220 - Set Feedrate Percentage: S<percent> ("FR" on your LCD) * M221 - Set Flow Percentage: S<percent> * M226 - Wait until the specified pin reaches the state required: P<pin number> S<pin state> * M240 - Trigger a camera to take a photograph * M250 - Set LCD contrast C<contrast value> (value 0..63) * M280 - Set servo position absolute. P: servo index, S: angle or microseconds * M300 - Play beep sound S<frequency Hz> P<duration ms> * M301 - Set PID parameters P I and D * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. * M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C) * M304 - Set bed PID parameters P I and D * M380 - Activate solenoid on active extruder * M381 - Disable all solenoids * M400 - Finish all moves * M401 - Lower Z probe if present * M402 - Raise Z probe if present * M404 - Display or set the Nominal Filament Width: [ N<diameter> ] * M405 - Enable Filament Sensor extrusion control. Optional delay between sensor and extruder: D<cm> * M406 - Disable Filament Sensor extrusion control * M407 - Display measured filament diameter in millimeters * M410 - Quickstop. Abort all the planned moves * M420 - Enable/Disable Mesh Leveling (with current values) S1=enable S0=disable * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> * M428 - Set the home_offset logically based on the current_position * M500 - Store parameters in EEPROM * M501 - Read parameters from EEPROM (if you need reset them after you changed them temporarily). * M502 - Revert to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. * M503 - Print the current settings (from memory not from EEPROM). Use S0 to leave off headings. * M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) * M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal] * M665 - Set delta configurations: L<diagonal rod> R<delta radius> S<segments/s> * M666 - Set delta endstop adjustment * M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ] * M851 - Set Z probe's Z offset in current units. (Negative values apply to probes that extend below the nozzle.) * M907 - Set digital trimpot motor current using axis codes. * M908 - Control digital trimpot directly. * M909 - DAC_STEPPER_CURRENT: Print digipot/DAC current value * M910 - DAC_STEPPER_CURRENT: Commit digipot/DAC value to external EEPROM via I2C * M350 - Set microstepping mode. * M351 - Toggle MS1 MS2 pins directly. * * ************ SCARA Specific - This can change to suit future G-code regulations * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration) * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree) * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration) * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree) * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position) * M365 - SCARA calibration: Scaling factor, X, Y, Z axis * ************* SCARA End *************** * * ************ Custom codes - This can change to suit future G-code regulations * M100 - Watch Free Memory (For Debugging Only) * M928 - Start SD logging (M928 filename.g) - ended by M29 * M999 - Restart after being stopped by error * * "T" Codes * * T0-T3 - Select a tool by index (usually an extruder) [ F<units/min> ] * */ bool Running = true; uint8_t marlin_debug_flags = DEBUG_NONE; float current_position[NUM_AXIS] = { 0.0 }; static float destination[NUM_AXIS] = { 0.0 }; bool axis_known_position[3] = { false }; bool axis_homed[3] = { false }; static bool send_ok[BUFSIZE]; static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0; static char command_queue[BUFSIZE][MAX_CMD_SIZE]; static char* current_command, *current_command_args; static uint8_t cmd_queue_index_r = 0, cmd_queue_index_w = 0, commands_in_queue = 0; #if ENABLED(INCH_MODE_SUPPORT) float linear_unit_factor = 1.0; float volumetric_unit_factor = 1.0; #endif #if ENABLED(TEMPERATURE_UNITS_SUPPORT) TempUnit input_temp_units = TEMPUNIT_C; #endif /** * Feed rates are often configured with mm/m * but the planner and stepper like mm/s units. */ const float homing_feedrate_mm_m[] = { #if ENABLED(DELTA) HOMING_FEEDRATE_Z, HOMING_FEEDRATE_Z, #else HOMING_FEEDRATE_XY, HOMING_FEEDRATE_XY, #endif HOMING_FEEDRATE_Z, 0 }; static float feedrate_mm_m = 1500.0, saved_feedrate_mm_m; int feedrate_percentage = 100, saved_feedrate_percentage; bool axis_relative_modes[] = AXIS_RELATIVE_MODES; int extruder_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); bool volumetric_enabled = false; float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA); float volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0); // The distance that XYZ has been offset by G92. Reset by G28. float position_shift[3] = { 0 }; // This offset is added to the configured home position. // Set by M206, M428, or menu item. Saved to EEPROM. float home_offset[3] = { 0 }; // Software Endstops. Default to configured limits. float sw_endstop_min[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS }; float sw_endstop_max[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS }; #if FAN_COUNT > 0 int fanSpeeds[FAN_COUNT] = { 0 }; #endif // The active extruder (tool). Set with T<extruder> command. uint8_t active_extruder = 0; // Relative Mode. Enable with G91, disable with G90. static bool relative_mode = false; volatile bool wait_for_heatup = true; const char errormagic[] PROGMEM = "Painter Error:"; const char echomagic[] PROGMEM = "Painter echo:"; const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'}; static int serial_count = 0; // GCode parameter pointer used by code_seen(), code_value_float(), etc. static char* seen_pointer; // Next Immediate GCode Command pointer. NULL if none. const char* queued_commands_P = NULL; const int sensitive_pins[] = SENSITIVE_PINS; ///< Sensitive pin list for M42 // Inactivity shutdown millis_t previous_cmd_ms = 0; static millis_t max_inactive_time = 0; static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL; // Print Job Timer #if ENABLED(PRINTCOUNTER) PrintCounter print_job_timer = PrintCounter(); #else Stopwatch print_job_timer = Stopwatch(); #endif static uint8_t target_extruder; #if HAS_BED_PROBE float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER; #endif #if ENABLED(AUTO_BED_LEVELING_FEATURE) #include "bed_vector_3.h" #if ENABLED(AUTO_BED_LEVELING_GRID) #include "bed_qr_solve.h" #endif #endif // AUTO_BED_LEVELING_FEATURE #define PLANNER_XY_FEEDRATE() (min(planner.max_feedrate_mm_s[X_AXIS], planner.max_feedrate_mm_s[Y_AXIS])) #if ENABLED(AUTO_BED_LEVELING_FEATURE) int xy_probe_feedrate_mm_m = XY_PROBE_SPEED; bool bed_leveling_in_progress = false; #define XY_PROBE_FEEDRATE_MM_M xy_probe_feedrate_mm_m #elif defined(XY_PROBE_SPEED) #define XY_PROBE_FEEDRATE_MM_M XY_PROBE_SPEED #else #define XY_PROBE_FEEDRATE_MM_M MMS_TO_MMM(PLANNER_XY_FEEDRATE()) #endif #if ENABLED(Z_DUAL_ENDSTOPS) && DISABLED(DELTA) float z_endstop_adj = 0; #endif // Extruder offsets #if HOTENDS > 1 float hotend_offset[][HOTENDS] = { HOTEND_OFFSET_X, HOTEND_OFFSET_Y #ifdef HOTEND_OFFSET_Z , HOTEND_OFFSET_Z #endif }; #endif #if HAS_Z_SERVO_ENDSTOP const int z_servo_angle[2] = Z_SERVO_ANGLES; #endif #if ENABLED(BARICUDA) int baricuda_valve_pressure = 0; int baricuda_e_to_p_pressure = 0; #endif #if ENABLED(FWRETRACT) bool autoretract_enabled = false; bool retracted[EXTRUDERS] = { false }; bool retracted_swap[EXTRUDERS] = { false }; float retract_length = RETRACT_LENGTH; float retract_length_swap = RETRACT_LENGTH_SWAP; float retract_feedrate_mm_s = RETRACT_FEEDRATE; float retract_zlift = RETRACT_ZLIFT; float retract_recover_length = RETRACT_RECOVER_LENGTH; float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP; float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE; #endif // FWRETRACT #if ENABLED(ULTIPANEL) && HAS_POWER_SWITCH bool powersupply = #if ENABLED(PS_DEFAULT_OFF) false #else true #endif ; #endif #if ENABLED(DELTA) #define TOWER_1 X_AXIS #define TOWER_2 Y_AXIS #define TOWER_3 Z_AXIS float delta[3]; float cartesian_position[3] = { 0 }; #define SIN_60 0.8660254037844386 #define COS_60 0.5 float endstop_adj[3] = { 0 }; // these are the default values, can be overriden with M665 float delta_radius = DELTA_RADIUS; float delta_tower1_x = -SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower float delta_tower1_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1); float delta_tower2_x = SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower float delta_tower2_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2); float delta_tower3_x = 0; // back middle tower float delta_tower3_y = (delta_radius + DELTA_RADIUS_TRIM_TOWER_3); float delta_diagonal_rod = DELTA_DIAGONAL_ROD; float delta_diagonal_rod_trim_tower_1 = DELTA_DIAGONAL_ROD_TRIM_TOWER_1; float delta_diagonal_rod_trim_tower_2 = DELTA_DIAGONAL_ROD_TRIM_TOWER_2; float delta_diagonal_rod_trim_tower_3 = DELTA_DIAGONAL_ROD_TRIM_TOWER_3; float delta_diagonal_rod_2_tower_1 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_1); float delta_diagonal_rod_2_tower_2 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_2); float delta_diagonal_rod_2_tower_3 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_3); float delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND; float delta_clip_start_height = Z_MAX_POS; #if ENABLED(AUTO_BED_LEVELING_FEATURE) int delta_grid_spacing[2] = { 0, 0 }; float bed_level[AUTO_BED_LEVELING_GRID_POINTS][AUTO_BED_LEVELING_GRID_POINTS]; #endif float delta_safe_distance_from_top(); #else static bool home_all_axis = true; #endif #if ENABLED(SCARA) float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND; float delta[3]; float axis_scaling[3] = { 1, 1, 1 }; // Build size scaling, default to 1 #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) //Variables for Filament Sensor input float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404 bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off float filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1]; //ring buffer to delay measurement store extruder factor after subtracting 100 int filwidth_delay_index1 = 0; //index into ring buffer int filwidth_delay_index2 = -1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting #endif #if ENABLED(FILAMENT_RUNOUT_SENSOR) static bool filament_ran_out = false; #endif #if ENABLED(FILAMENT_CHANGE_FEATURE) FilamentChangeMenuResponse filament_change_menu_response; #endif #if ENABLED(MIXING_EXTRUDER) float mixing_factor[MIXING_STEPPERS]; #if MIXING_VIRTUAL_TOOLS > 1 float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; #endif #endif #if HAS_SERVOS Servo servo[NUM_SERVOS]; #define MOVE_SERVO(I, P) servo[I].move(P) #if HAS_Z_SERVO_ENDSTOP #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0]) #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1]) #endif #endif #ifdef CHDK millis_t chdkHigh = 0; boolean chdkActive = false; #endif #if ENABLED(PID_EXTRUSION_SCALING) int lpq_len = 20; #endif #if ENABLED(HOST_KEEPALIVE_FEATURE) static MarlinBusyState busy_state = NOT_BUSY; static millis_t next_busy_signal_ms = 0; uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL; #define KEEPALIVE_STATE(n) do{ busy_state = n; } while(0) #else #define host_keepalive() ; #define KEEPALIVE_STATE(n) ; #endif // HOST_KEEPALIVE_FEATURE /** * *************************************************************************** * ******************************** FUNCTIONS ******************************** * *************************************************************************** */ void stop(); void get_available_commands(); void process_next_command(); void prepare_move_to_destination(); void set_current_from_steppers_for_axis(AxisEnum axis); #if ENABLED(SDSUPPORT) #include "SdFatUtil.h" int freeMemory() { return SdFatUtil::FreeRam(); } #endif //!SDSUPPORT #if ENABLED(ARC_SUPPORT) void plan_arc(float target[NUM_AXIS], float* offset, uint8_t clockwise); #endif #if ENABLED(BEZIER_CURVE_SUPPORT) void plan_cubic_move(const float offset[4]); #endif void serial_echopair_P(const char* s_P, char v) { serialprintPGM(s_P); SERIAL_CHAR(v); } void serial_echopair_P(const char* s_P, int v) { serialprintPGM(s_P); SERIAL_ECHO(v); } void serial_echopair_P(const char* s_P, long v) { serialprintPGM(s_P); SERIAL_ECHO(v); } void serial_echopair_P(const char* s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); } void serial_echopair_P(const char* s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); } void serial_echopair_P(const char* s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); } void tool_change(const uint8_t tmp_extruder, const float fr_mm_m=0.0, bool no_move=false); static void report_current_position(); /////////////////////////////////////// DEBUG_LEVELING_FEATURE /////////////////////////////////////////////// #if ENABLED(DEBUG_LEVELING_FEATURE) void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) { serialprintPGM(prefix); SERIAL_ECHOPAIR("(", x); SERIAL_ECHOPAIR(", ", y); SERIAL_ECHOPAIR(", ", z); SERIAL_ECHOPGM(")leveling debug"); if (suffix) serialprintPGM(suffix); else SERIAL_EOL; } void print_xyz(const char* prefix, const char* suffix, const float xyz[]) { print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]); } #if ENABLED(AUTO_BED_LEVELING_FEATURE) void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) { print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z); } #endif #define DEBUG_POS(SUFFIX,VAR) do { \ print_xyz(PSTR(STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); } while(0) #endif inline void sync_plan_position() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position); #endif planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); } inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); } #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position() /** * Inject the next "immediate" command, when possible. * Return true if any immediate commands remain to inject. */ static bool drain_queued_commands_P() { if (queued_commands_P != NULL) { size_t i = 0; char c, cmd[30]; strncpy_P(cmd, queued_commands_P, sizeof(cmd) - 1); cmd[sizeof(cmd) - 1] = '\0'; while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command cmd[i] = '\0'; if (enqueue_and_echo_command(cmd)) { // success? if (c) // newline char? queued_commands_P += i + 1; // advance to the next command else queued_commands_P = NULL; // nul char? no more commands } } return (queued_commands_P != NULL); // return whether any more remain } /** * Record one or many commands to run from program memory. * Aborts the current queue, if any. * Note: drain_queued_commands_P() must be called repeatedly to drain the commands afterwards */ void enqueue_and_echo_commands_P(const char* pgcode) { queued_commands_P = pgcode; drain_queued_commands_P(); // first command executed asap (when possible) } void clear_command_queue() { cmd_queue_index_r = cmd_queue_index_w; commands_in_queue = 0; } inline void _commit_command(bool say_ok) { send_ok[cmd_queue_index_w] = say_ok; cmd_queue_index_w = (cmd_queue_index_w + 1) % BUFSIZE; commands_in_queue++; } /** * Copy a command directly into the main command buffer, from RAM. * Returns true if successfully adds the command */ inline bool _enqueuecommand(const char* cmd, bool say_ok=false) { if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false; strcpy(command_queue[cmd_queue_index_w], cmd); _commit_command(say_ok); return true; } void enqueue_and_echo_command_now(const char* cmd) { while (!enqueue_and_echo_command(cmd)) idle(); } bool enqueue_and_echo_command(const char* cmd, bool say_ok /*=false*/ ) { if (_enqueuecommand(cmd, say_ok)) { SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_Enqueueing); SERIAL_ECHO(cmd); SERIAL_ECHOLNPGM("\""); return true; } return false; } #if ENABLED(FILAMENT_RUNOUT_SENSOR) void setup_filrunoutpin() { pinMode(FIL_RUNOUT_PIN, INPUT); pinMode(FIL_1_RUNOUT_PIN, INPUT); pinMode(FIL_2_RUNOUT_PIN, INPUT); pinMode(FIL_3_RUNOUT_PIN, INPUT); #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT) WRITE(FIL_RUNOUT_PIN, HIGH); WRITE(FIL_1_RUNOUT_PIN, HIGH); WRITE(FIL_2_RUNOUT_PIN, HIGH); WRITE(FIL_3_RUNOUT_PIN, HIGH); #endif } #endif // Set home pin void setup_homepin(void) { #if HAS_HOME SET_INPUT(HOME_PIN); WRITE(HOME_PIN, HIGH); #endif } void setup_photpin() { #if HAS_PHOTOGRAPH OUT_WRITE(PHOTOGRAPH_PIN, LOW); #endif } void setup_powerhold() { #if HAS_SUICIDE OUT_WRITE(SUICIDE_PIN, HIGH); #endif #if HAS_POWER_SWITCH #if ENABLED(PS_DEFAULT_OFF) OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP); #else OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); #endif #endif } void suicide() { #if HAS_SUICIDE OUT_WRITE(SUICIDE_PIN, LOW); #endif } void servo_init() { #if NUM_SERVOS >= 1 && HAS_SERVO_0 servo[0].attach(SERVO0_PIN); servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position. #endif #if NUM_SERVOS >= 2 && HAS_SERVO_1 servo[1].attach(SERVO1_PIN); servo[1].detach(); #endif #if NUM_SERVOS >= 3 && HAS_SERVO_2 servo[2].attach(SERVO2_PIN); servo[2].detach(); #endif #if NUM_SERVOS >= 4 && HAS_SERVO_3 servo[3].attach(SERVO3_PIN); servo[3].detach(); #endif #if HAS_Z_SERVO_ENDSTOP /** * Set position of Z Servo Endstop * * The servo might be deployed and positioned too low to stow * when starting up the machine or rebooting the board. * There's no way to know where the nozzle is positioned until * homing has been done - no homing with z-probe without init! * */ STOW_Z_SERVO(); #endif #if HAS_BED_PROBE endstops.enable_z_probe(false); #endif } #if HAS_STEPPER_RESET void disableStepperDrivers() { pinMode(STEPPER_RESET_PIN, OUTPUT); digitalWrite(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips } void enableStepperDrivers() { pinMode(STEPPER_RESET_PIN, INPUT); } // set to input, which allows it to be pulled high by pullups #endif #if ENABLED(DIGIPOT_I2C) extern void digipot_i2c_set_current(int channel, float current); extern void digipot_i2c_init(); #endif void setup_killpin() { #if HAS_KILL SET_INPUT(KILL_PIN); WRITE(KILL_PIN, HIGH); #endif } void setup() { #if ENABLED(FILAMENT_RUNOUT_SENSOR) setup_filrunoutpin(); #endif setup_killpin(); setup_powerhold(); #if HAS_STEPPER_RESET disableStepperDrivers(); #endif MYSERIAL.begin(BAUDRATE); SERIAL_PROTOCOLLNPGM("Now Painter running(setup)"); SERIAL_ECHO_START; // Check startup - does nothing if bootloader sets MCUSR to 0 byte mcu = MCUSR; if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP); if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET); if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET); if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET); if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET); MCUSR = 0; SERIAL_ECHOPGM(MSG_MARLIN); SERIAL_ECHOLNPGM(" Painter " SHORT_BUILD_VERSION); #ifdef STRING_DISTRIBUTION_DATE #ifdef STRING_CONFIG_H_AUTHOR SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_CONFIGURATION_VER); SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE); SERIAL_ECHOPGM(MSG_AUTHOR); SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR); SERIAL_ECHOPGM("Compiled: "); SERIAL_ECHOLNPGM(__DATE__); #endif // STRING_CONFIG_H_AUTHOR #endif // STRING_DISTRIBUTION_DATE SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_FREE_MEMORY); SERIAL_ECHO(freeMemory()); SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES); SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE); // Send "ok" after commands by default for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true; // Load data from EEPROM if available (or use defaults) // This also updates variables in the planner, elsewhere Config_RetrieveSettings(); // Initialize current position based on home_offset memcpy(current_position, home_offset, sizeof(home_offset)); // Vital to init stepper/planner equivalent for current_position SYNC_PLAN_POSITION_KINEMATIC(); thermalManager.init(); // Initialize temperature loop #if ENABLED(USE_WATCHDOG) watchdog_init(); #endif stepper.init(); // Initialize stepper, this enables interrupts! setup_photpin(); // OUT_WRITE(PHOTOGRAPH_PIN, LOW); servo_init(); #if HAS_CONTROLLERFAN SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan #endif #if HAS_VACCUM SET_OUTPUT(VACCUM_PIN); #endif #if HAS_AIR SET_OUTPUT(AIR_PIN); #endif #if HAS_STEPPER_RESET enableStepperDrivers(); #endif #if ENABLED(DIGIPOT_I2C) digipot_i2c_init(); #endif #if ENABLED(DAC_STEPPER_CURRENT) dac_init(); #endif #if ENABLED(Z_PROBE_SLED) && PIN_EXISTS(SLED) pinMode(SLED_PIN, OUTPUT); digitalWrite(SLED_PIN, LOW); // turn it off #endif // Z_PROBE_SLED setup_homepin(); lcd_init(); #if ENABLED(SHOW_BOOTSCREEN) #if ENABLED(DOGLCD) safe_delay(BOOTSCREEN_TIMEOUT); #elif ENABLED(ULTRA_LCD) bootscreen(); lcd_init(); #endif #endif #if ENABLED(SHOW_LED) #if ENABLED(WS8212A_PIN) pinMode(WS8212A_PIN, OUTPUT); digitalWrite(WS8212A_PIN, LOW); #endif #if ENABLED(WS8212B_PIN) pinMode(WS8212B_PIN, OUTPUT); digitalWrite(WS8212B_PIN, LOW); #endif #endif // analogWrite(HEATER_BED_PIN,255); // delay(1000); // analogWrite(HEATER_BED_PIN,55); } /** * The main Marlin program loop * * - Save or log commands to SD * - Process available commands (if not saving) * - Call heater manager * - Call inactivity manager * - Call endstop manager * - Call LCD update */ void loop() { if (commands_in_queue < BUFSIZE) get_available_commands(); #if ENABLED(SDSUPPORT) card.checkautostart(false); #endif if (commands_in_queue) { #if ENABLED(SDSUPPORT) if (card.saving) { char* command = command_queue[cmd_queue_index_r]; if (strstr_P(command, PSTR("M29"))) { // M29 closes the file card.closefile(); SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED); ok_to_send(); } else { // Write the string from the read buffer to SD card.write_command(command); if (card.logging) process_next_command(); // The card is saving because it's logging else ok_to_send(); } } else process_next_command(); #else process_next_command(); #endif // SDSUPPORT // The queue may be reset by a command handler or by code invoked by idle() within a handler if (commands_in_queue) { --commands_in_queue; cmd_queue_index_r = (cmd_queue_index_r + 1) % BUFSIZE; } } endstops.report_state(); idle(); } //end loop void gcode_line_error(const char* err, bool doFlush = true) { SERIAL_ERROR_START; serialprintPGM(err); SERIAL_ERRORLN(gcode_LastN); //Serial.println(gcode_N); if (doFlush) FlushSerialRequestResend(); serial_count = 0; } inline void get_serial_commands() { static char serial_line_buffer[MAX_CMD_SIZE]; static boolean serial_comment_mode = false; // If the command buffer is empty for too long, send "wait" to indicate Marlin is still waiting. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0 static millis_t last_command_time = 0; millis_t ms = millis(); if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) { SERIAL_ECHOLNPGM(MSG_WAIT); last_command_time = ms; } #endif /** * Loop while serial characters are incoming and the queue is not full */ while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) { char serial_char = MYSERIAL.read(); /** * If the character ends the line */ if (serial_char == '\n' || serial_char == '\r') { serial_comment_mode = false; // end of line == end of comment if (!serial_count) continue; // skip empty lines serial_line_buffer[serial_count] = 0; // terminate string serial_count = 0; //reset buffer char* command = serial_line_buffer; while (*command == ' ') command++; // skip any leading spaces char* npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line char* apos = strchr(command, '*'); if (npos) { boolean M110 = strstr_P(command, PSTR("M110")) != NULL; if (M110) { char* n2pos = strchr(command + 4, 'N'); if (n2pos) npos = n2pos; } gcode_N = strtol(npos + 1, NULL, 10); if (gcode_N != gcode_LastN + 1 && !M110) { gcode_line_error(PSTR(MSG_ERR_LINE_NO)); return; } if (apos) { byte checksum = 0, count = 0; while (command[count] != '*') checksum ^= command[count++]; if (strtol(apos + 1, NULL, 10) != checksum) { gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH)); return; } // if no errors, continue parsing } else { gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM)); return; } gcode_LastN = gcode_N; // if no errors, continue parsing } else if (apos) { // No '*' without 'N' gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false); return; } // Movement commands alert when stopped if (IsStopped()) { char* gpos = strchr(command, 'G'); if (gpos) { int codenum = strtol(gpos + 1, NULL, 10); switch (codenum) { case 0: case 1: case 2: case 3: SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); LCD_MESSAGEPGM(MSG_STOPPED); break; } } } #if DISABLED(EMERGENCY_PARSER) // If command was e-stop process now if (strcmp(command, "M108") == 0) wait_for_heatup = false; if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED)); if (strcmp(command, "M410") == 0) { quickstop_stepper(); } #endif #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0 last_command_time = ms; #endif // Add the command to the queue _enqueuecommand(serial_line_buffer, true); } else if (serial_count >= MAX_CMD_SIZE - 1) { // Keep fetching, but ignore normal characters beyond the max length // The command will be injected when EOL is reached } else if (serial_char == '\\') { // Handle escapes if (MYSERIAL.available() > 0) { // if we have one more character, copy it over serial_char = MYSERIAL.read(); if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char; } } else { // it's not a newline, carriage return or escape char if (serial_char == ';') serial_comment_mode = true; if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char; } } // queue has space, serial has data } #if ENABLED(SDSUPPORT) inline void get_sdcard_commands() { if (!card.sdprinting) return; static bool stop_buffering = false, sd_comment_mode = false; uint16_t sd_count = 0; bool card_eof = card.eof(); if (commands_in_queue == 0) stop_buffering = false; /** * '#' stops reading from SD to the buffer prematurely, so procedural * macro calls are possible. If it occurs, stop_buffering is triggered * and the buffer is run dry; this character _can_ occur in serial com * due to checksums, however, no checksums are used in SD printing. */ while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) { int16_t n = card.get(); char sd_char = (char)n; card_eof = card.eof(); if (card_eof || n == -1 || sd_char == '\n' || sd_char == '\r' || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)) { if (card_eof) { SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED); card.printingHasFinished(); card.checkautostart(true); } else if (n == -1) { SERIAL_ERROR_START; SERIAL_ECHOLNPGM(MSG_SD_ERR_READ); } if (sd_char == '#') stop_buffering = true; sd_comment_mode = false; //for new command if (!sd_count) continue; //skip empty lines command_queue[cmd_queue_index_w][sd_count] = '\0'; //terminate string sd_count = 0; //clear buffer _commit_command(false); } else if (sd_count >= MAX_CMD_SIZE - 1) { /** * Keep fetching, but ignore normal characters beyond the max length * The command will be injected when EOL is reached */ } else { if (sd_char == ';') sd_comment_mode = true; if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char; } } } #endif // SDSUPPORT void get_available_commands() { // if any immediate commands remain, don't get other commands yet if (drain_queued_commands_P()) return; get_serial_commands(); #if ENABLED(SDSUPPORT) get_sdcard_commands(); #endif } inline bool code_has_value() { int i = 1; char c = seen_pointer[i]; while (c == ' ') c = seen_pointer[++i]; if (c == '-' || c == '+') c = seen_pointer[++i]; if (c == '.') c = seen_pointer[++i]; return NUMERIC(c); } inline float code_value_float() { float ret; char* e = strchr(seen_pointer, 'E'); if (e) { *e = 0; ret = strtod(seen_pointer + 1, NULL); *e = 'E'; } else ret = strtod(seen_pointer + 1, NULL); return ret; } inline unsigned long code_value_ulong() { return strtoul(seen_pointer + 1, NULL, 10); } inline long code_value_long() { return strtol(seen_pointer + 1, NULL, 10); } inline int code_value_int() { return (int)strtol(seen_pointer + 1, NULL, 10); } inline uint16_t code_value_ushort() { return (uint16_t)strtoul(seen_pointer + 1, NULL, 10); } inline uint8_t code_value_byte() { return (uint8_t)(constrain(strtol(seen_pointer + 1, NULL, 10), 0, 255)); } inline bool code_value_bool() { return code_value_byte() > 0; } #if ENABLED(INCH_MODE_SUPPORT) inline void set_input_linear_units(LinearUnit units) { switch (units) { case LINEARUNIT_INCH: linear_unit_factor = 25.4; break; case LINEARUNIT_MM: default: linear_unit_factor = 1.0; break; } volumetric_unit_factor = pow(linear_unit_factor, 3.0); } inline float axis_unit_factor(int axis) { return (axis == E_AXIS && volumetric_enabled ? volumetric_unit_factor : linear_unit_factor); } inline float code_value_linear_units() { return code_value_float() * linear_unit_factor; } inline float code_value_axis_units(int axis) { return code_value_float() * axis_unit_factor(axis); } inline float code_value_per_axis_unit(int axis) { return code_value_float() / axis_unit_factor(axis); } #else inline float code_value_linear_units() { return code_value_float(); } inline float code_value_axis_units(int axis) { UNUSED(axis); return code_value_float(); } inline float code_value_per_axis_unit(int axis) { UNUSED(axis); return code_value_float(); } #endif #if ENABLED(TEMPERATURE_UNITS_SUPPORT) inline void set_input_temp_units(TempUnit units) { input_temp_units = units; } float code_value_temp_abs() { switch (input_temp_units) { case TEMPUNIT_C: return code_value_float(); case TEMPUNIT_F: return (code_value_float() - 32) * 0.5555555556; case TEMPUNIT_K: return code_value_float() - 272.15; default: return code_value_float(); } } float code_value_temp_diff() { switch (input_temp_units) { case TEMPUNIT_C: case TEMPUNIT_K: return code_value_float(); case TEMPUNIT_F: return code_value_float() * 0.5555555556; default: return code_value_float(); } } #else float code_value_temp_abs() { return code_value_float(); } float code_value_temp_diff() { return code_value_float(); } #endif FORCE_INLINE millis_t code_value_millis() { return code_value_ulong(); } inline millis_t code_value_millis_from_seconds() { return code_value_float() * 1000; } bool code_seen(char code) { seen_pointer = strchr(current_command_args, code); return (seen_pointer != NULL); // Return TRUE if the code-letter was found } /** * Set target_extruder from the T parameter or the active_extruder * * Returns TRUE if the target is invalid */ bool get_target_extruder_from_command(int code) { if (code_seen('T')) { if (code_value_byte() >= EXTRUDERS) { SERIAL_ECHO_START; SERIAL_CHAR('M'); SERIAL_ECHO(code); SERIAL_ECHOPAIR(" " MSG_INVALID_EXTRUDER " ", code_value_byte()); SERIAL_EOL; return true; } target_extruder = code_value_byte(); } else target_extruder = active_extruder; return false; } #define DEFINE_PGM_READ_ANY(type, reader) \ static inline type pgm_read_any(const type *p) \ { return pgm_read_##reader##_near(p); } DEFINE_PGM_READ_ANY(float, float); DEFINE_PGM_READ_ANY(signed char, byte); #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \ static const PROGMEM type array##_P[3] = \ { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \ static inline type array(int axis) \ { return pgm_read_any(&array##_P[axis]); } XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS); XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS); XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS); XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH); XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM); XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR); #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE) bool extruder_duplication_enabled = false; // Used in Dual X mode 2 #endif #if ENABLED(DUAL_X_CARRIAGE) #define DXC_FULL_CONTROL_MODE 0 #define DXC_AUTO_PARK_MODE 1 #define DXC_DUPLICATION_MODE 2 static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; static float x_home_pos(int extruder) { if (extruder == 0) return LOGICAL_X_POSITION(base_home_pos(X_AXIS)); else /** * In dual carriage mode the extruder offset provides an override of the * second X-carriage offset when homed - otherwise X2_HOME_POS is used. * This allow soft recalibration of the second extruder offset position * without firmware reflash (through the M218 command). */ return (hotend_offset[X_AXIS][1] > 0) ? hotend_offset[X_AXIS][1] : X2_HOME_POS; } static int x_home_dir(int extruder) { return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR; } static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1 static bool active_extruder_parked = false; // used in mode 1 & 2 static float raised_parked_position[NUM_AXIS]; // used in mode 1 static millis_t delayed_move_time = 0; // used in mode 1 static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2 static float duplicate_extruder_temp_offset = 0; // used in mode 2 #endif //DUAL_X_CARRIAGE /** * Software endstops can be used to monitor the open end of * an axis that has a hardware endstop on the other end. Or * they can prevent axes from moving past endstops and grinding. * * To keep doing their job as the coordinate system changes, * the software endstop positions must be refreshed to remain * at the same positions relative to the machine. */ static void update_software_endstops(AxisEnum axis) { float offs = LOGICAL_POSITION(0, axis); { sw_endstop_min[axis] = base_min_pos(axis) + offs; sw_endstop_max[axis] = base_max_pos(axis) + offs; } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("For ", axis_codes[axis]); SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]); SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]); SERIAL_ECHOPAIR("\n sw_endstop_min = ", sw_endstop_min[axis]); SERIAL_ECHOPAIR("\n sw_endstop_max = ", sw_endstop_max[axis]); SERIAL_EOL; } #endif } /** * Change the home offset for an axis, update the current * position and the software endstops to retain the same * relative distance to the new home. * * Since this changes the current_position, code should * call sync_plan_position soon after this. */ static void set_home_offset(AxisEnum axis, float v) { current_position[axis] += v - home_offset[axis]; home_offset[axis] = v; update_software_endstops(axis); } static void set_axis_is_at_home(AxisEnum axis) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis); SERIAL_ECHOLNPGM(")"); } #endif position_shift[axis] = 0; #if ENABLED(DUAL_X_CARRIAGE) if (axis == X_AXIS && (active_extruder != 0 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) { if (active_extruder != 0) current_position[X_AXIS] = x_home_pos(active_extruder); else current_position[X_AXIS] = LOGICAL_X_POSITION(base_home_pos(X_AXIS)); update_software_endstops(X_AXIS); return; } #endif #if ENABLED(SCARA) if (axis == X_AXIS || axis == Y_AXIS) { float homeposition[3]; LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos(i), i); // SERIAL_ECHOPGM("homeposition[x]= "); SERIAL_ECHO(homeposition[0]); // SERIAL_ECHOPGM("homeposition[y]= "); SERIAL_ECHOLN(homeposition[1]); /** * Works out real Homeposition angles using inverse kinematics, * and calculates homing offset using forward kinematics */ inverse_kinematics(homeposition); forward_kinematics_SCARA(delta); // SERIAL_ECHOPAIR("Delta X=", delta[X_AXIS]); // SERIAL_ECHOPGM(" Delta Y="); SERIAL_ECHOLN(delta[Y_AXIS]); current_position[axis] = LOGICAL_POSITION(delta[axis], axis); /** * SCARA home positions are based on configuration since the actual * limits are determined by the inverse kinematic transform. */ sw_endstop_min[axis] = base_min_pos(axis); // + (delta[axis] - base_home_pos(axis)); sw_endstop_max[axis] = base_max_pos(axis); // + (delta[axis] - base_home_pos(axis)); } else #endif { current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis); update_software_endstops(axis); #if HAS_BED_PROBE && Z_HOME_DIR < 0 && DISABLED(Z_MIN_PROBE_ENDSTOP) if (axis == Z_AXIS) { current_position[Z_AXIS] -= zprobe_zoffset; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("> zprobe_zoffset = ", zprobe_zoffset); SERIAL_EOL; } #endif } #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]); SERIAL_ECHOPAIR("] = ", home_offset[axis]); SERIAL_EOL; DEBUG_POS("", current_position); } #endif } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis); SERIAL_ECHOLNPGM(")"); } #endif } /** * Some planner shorthand inline functions */ inline float get_homing_bump_feedrate(AxisEnum axis) { const int homing_bump_divisor[] = HOMING_BUMP_DIVISOR; int hbd = homing_bump_divisor[axis]; if (hbd < 1) { hbd = 10; SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1"); } return homing_feedrate_mm_m[axis] / hbd; } // // line_to_current_position // Move the planner to the current position from wherever it last moved // (or from wherever it has been told it is located). // inline void line_to_current_position() { planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], MMM_TO_MMS(feedrate_mm_m), active_extruder); } inline void line_to_z(float zPosition) { planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], MMM_TO_MMS(feedrate_mm_m), active_extruder); } inline void line_to_axis_pos(AxisEnum axis, float where, float fr_mm_m = 0.0) { float old_feedrate_mm_m = feedrate_mm_m; current_position[axis] = where; feedrate_mm_m = (fr_mm_m != 0.0) ? fr_mm_m : homing_feedrate_mm_m[axis]; planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], MMM_TO_MMS(feedrate_mm_m), active_extruder); stepper.synchronize(); feedrate_mm_m = old_feedrate_mm_m; } // // line_to_destination // Move the planner, not necessarily synced with current_position // inline void line_to_destination(float fr_mm_m) { planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], MMM_TO_MMS(fr_mm_m), active_extruder); } inline void line_to_destination() { line_to_destination(feedrate_mm_m); } inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); } inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); } /** * Plan a move to (X, Y, Z) and set the current_position * The final current_position may not be the one that was requested */ void do_blocking_move_to(float x, float y, float z, float fr_mm_m /*=0.0*/) { float old_feedrate_mm_m = feedrate_mm_m; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, x, y, z); #endif #if ENABLED(DELTA) feedrate_mm_m = (fr_mm_m != 0.0) ? fr_mm_m : XY_PROBE_FEEDRATE_MM_M; set_destination_to_current(); // sync destination at the start #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination); #endif // when in the danger zone if (current_position[Z_AXIS] > delta_clip_start_height) { if (z > delta_clip_start_height) { // staying in the danger zone destination[X_AXIS] = x; // move directly (uninterpolated) destination[Y_AXIS] = y; destination[Z_AXIS] = z; prepare_move_to_destination_raw(); // set_current_to_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position); #endif return; } else { destination[Z_AXIS] = delta_clip_start_height; prepare_move_to_destination_raw(); // set_current_to_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position); #endif } } if (z > current_position[Z_AXIS]) { // raising? destination[Z_AXIS] = z; prepare_move_to_destination_raw(); // set_current_to_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position); #endif } destination[X_AXIS] = x; destination[Y_AXIS] = y; prepare_move_to_destination(); // set_current_to_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position); #endif if (z < current_position[Z_AXIS]) { // lowering? destination[Z_AXIS] = z; prepare_move_to_destination_raw(); // set_current_to_destination #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position); #endif } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to"); #endif #else // If Z needs to raise, do it before moving XY if (current_position[Z_AXIS] < z) { feedrate_mm_m = (fr_mm_m != 0.0) ? fr_mm_m : homing_feedrate_mm_m[Z_AXIS]; current_position[Z_AXIS] = z; line_to_current_position(); } feedrate_mm_m = (fr_mm_m != 0.0) ? fr_mm_m : XY_PROBE_FEEDRATE_MM_M; current_position[X_AXIS] = x; current_position[Y_AXIS] = y; line_to_current_position(); // If Z needs to lower, do it after moving XY if (current_position[Z_AXIS] > z) { feedrate_mm_m = (fr_mm_m != 0.0) ? fr_mm_m : homing_feedrate_mm_m[Z_AXIS]; current_position[Z_AXIS] = z; line_to_current_position(); } #endif stepper.synchronize(); feedrate_mm_m = old_feedrate_mm_m; } void do_blocking_move_to_x(float x, float fr_mm_m/*=0.0*/) { do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_m); } void do_blocking_move_to_z(float z, float fr_mm_m/*=0.0*/) { do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z, fr_mm_m); } void do_blocking_move_to_xy(float x, float y, float fr_mm_m/*=0.0*/) { do_blocking_move_to(x, y, current_position[Z_AXIS], fr_mm_m); } // // Prepare to do endstop or probe moves // with custom feedrates. // // - Save current feedrates // - Reset the rate multiplier // - Reset the command timeout // - Enable the endstops (for endstop moves) // static void setup_for_endstop_or_probe_move() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position); #endif saved_feedrate_mm_m = feedrate_mm_m; saved_feedrate_percentage = feedrate_percentage; feedrate_percentage = 100; refresh_cmd_timeout(); } static void clean_up_after_endstop_or_probe_move() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position); #endif feedrate_mm_m = saved_feedrate_mm_m; feedrate_percentage = saved_feedrate_percentage; refresh_cmd_timeout(); } #if HAS_BED_PROBE /** * Raise Z to a minimum height to make room for a probe to move */ inline void do_probe_raise(float z_raise) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("do_probe_raise(", z_raise); SERIAL_ECHOLNPGM(")"); } #endif float z_dest = LOGICAL_Z_POSITION(z_raise); if (z_dest > current_position[Z_AXIS]) do_blocking_move_to_z(z_dest); } #endif //HAS_BED_PROBE #if ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED) || ENABLED(Z_SAFE_HOMING) || HAS_PROBING_PROCEDURE || HOTENDS > 1 || ENABLED(NOZZLE_CLEAN_FEATURE) || ENABLED(NOZZLE_PARK_FEATURE) static bool axis_unhomed_error(const bool x, const bool y, const bool z) { const bool xx = x && !axis_homed[X_AXIS], yy = y && !axis_homed[Y_AXIS], zz = z && !axis_homed[Z_AXIS]; if (xx || yy || zz) { SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_HOME " "); if (xx) SERIAL_ECHOPGM(MSG_X); if (yy) SERIAL_ECHOPGM(MSG_Y); if (zz) SERIAL_ECHOPGM(MSG_Z); SERIAL_ECHOLNPGM(" " MSG_FIRST); #if ENABLED(ULTRA_LCD) char message[3 * (LCD_WIDTH) + 1] = ""; // worst case is kana.utf with up to 3*LCD_WIDTH+1 strcat_P(message, PSTR(MSG_HOME " ")); if (xx) strcat_P(message, PSTR(MSG_X)); if (yy) strcat_P(message, PSTR(MSG_Y)); if (zz) strcat_P(message, PSTR(MSG_Z)); strcat_P(message, PSTR(" " MSG_FIRST)); lcd_setstatus(message); #endif return true; } return false; } #endif #if ENABLED(Z_PROBE_SLED) #ifndef SLED_DOCKING_OFFSET #define SLED_DOCKING_OFFSET 0 #endif /** * Method to dock/undock a sled designed by Charles Bell. * * stow[in] If false, move to MAX_X and engage the solenoid * If true, move to MAX_X and release the solenoid */ static void dock_sled(bool stow) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("dock_sled(", stow); SERIAL_ECHOLNPGM(")"); } #endif // Dock sled a bit closer to ensure proper capturing do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0)); #if PIN_EXISTS(SLED) digitalWrite(SLED_PIN, !stow); // switch solenoid #endif } #endif // Z_PROBE_SLED #if ENABLED(Z_PROBE_ALLEN_KEY) void run_deploy_moves_script() { #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z, Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z, Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z, Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z, Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Z) #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z, Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE); #endif } void run_stow_moves_script() { #if defined(Z_PROBE_ALLEN_KEY_STOW_1_X) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z, Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_2_X) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z, Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_3_X) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z, Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_4_X) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z, Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE); #endif #if defined(Z_PROBE_ALLEN_KEY_STOW_5_X) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Z) #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS] #endif #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0 #endif do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z, Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE); #endif } #endif #if HAS_BED_PROBE // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST) #if ENABLED(Z_MIN_PROBE_ENDSTOP) #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING) #else #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING) #endif #endif #define DEPLOY_PROBE() set_probe_deployed( true ) #define STOW_PROBE() set_probe_deployed( false ) // returns false for ok and true for failure static bool set_probe_deployed(bool deploy) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { DEBUG_POS("set_probe_deployed", current_position); SERIAL_ECHOPAIR("deploy: ", deploy); SERIAL_EOL; } #endif if (endstops.z_probe_enabled == deploy) return false; // Make room for probe do_probe_raise(_Z_PROBE_DEPLOY_HEIGHT); #if ENABLED(Z_PROBE_SLED) if (axis_unhomed_error(true, false, false)) { stop(); return true; } #elif ENABLED(Z_PROBE_ALLEN_KEY) if (axis_unhomed_error(true, true, true )) { stop(); return true; } #endif float oldXpos = current_position[X_AXIS]; // save x position float oldYpos = current_position[Y_AXIS]; // save y position #ifdef _TRIGGERED_WHEN_STOWED_TEST // If endstop is already false, the Z probe is deployed if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions. // Would a goto be less ugly? //while (!_TRIGGERED_WHEN_STOWED_TEST) { idle(); // would offer the opportunity // for a triggered when stowed manual probe. #endif #if ENABLED(Z_PROBE_SLED) dock_sled(!deploy); #elif HAS_Z_SERVO_ENDSTOP servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[((deploy) ? 0 : 1)]); #elif ENABLED(Z_PROBE_ALLEN_KEY) if (!deploy) run_stow_moves_script(); else run_deploy_moves_script(); #else // Nothing to be done. Just enable_z_probe below... #endif #ifdef _TRIGGERED_WHEN_STOWED_TEST }; // opened before the probe specific actions if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { if (IsRunning()) { SERIAL_ERROR_START; SERIAL_ERRORLNPGM("Z-Probe failed"); LCD_ALERTMESSAGEPGM("Err: ZPROBE"); } stop(); return true; } #endif do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy endstops.enable_z_probe( deploy ); return false; } // Do a single Z probe and return with current_position[Z_AXIS] // at the height where the probe triggered. static float run_z_probe() { // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding refresh_cmd_timeout(); #if ENABLED(AUTO_BED_LEVELING_FEATURE) planner.bed_level_matrix.set_to_identity(); #endif #if ENABLED(PROBE_DOUBLE_TOUCH) do_blocking_move_to_z(-(Z_MAX_LENGTH + 10), Z_PROBE_SPEED_FAST); endstops.hit_on_purpose(); set_current_from_steppers_for_axis(Z_AXIS); SYNC_PLAN_POSITION_KINEMATIC(); // move up the retract distance do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), Z_PROBE_SPEED_FAST); #else // move fast, close to the bed do_blocking_move_to_z(home_bump_mm(Z_AXIS), Z_PROBE_SPEED_FAST); #endif // move down slowly to find bed do_blocking_move_to_z(current_position[Z_AXIS] -2.0*home_bump_mm(Z_AXIS), Z_PROBE_SPEED_SLOW); endstops.hit_on_purpose(); set_current_from_steppers_for_axis(Z_AXIS); SYNC_PLAN_POSITION_KINEMATIC(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("run_z_probe", current_position); #endif return current_position[Z_AXIS]; } // // - Move to the given XY // - Deploy the probe, if not already deployed // - Probe the bed, get the Z position // - Depending on the 'stow' flag // - Stow the probe, or // - Raise to the BETWEEN height // - Return the probed Z position // static float probe_pt(float x, float y, bool stow = true, int verbose_level = 1) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> probe_pt(", x); SERIAL_ECHOPAIR(", ", y); SERIAL_ECHOPAIR(", ", stow ? "stow" : "no stow"); SERIAL_ECHOLNPGM(")"); DEBUG_POS("", current_position); } #endif float old_feedrate_mm_m = feedrate_mm_m; // Ensure a minimum height before moving the probe do_probe_raise(Z_PROBE_TRAVEL_HEIGHT); // Move to the XY where we shall probe #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("> do_blocking_move_to_xy(", x - (X_PROBE_OFFSET_FROM_EXTRUDER)); SERIAL_ECHOPAIR(", ", y - (Y_PROBE_OFFSET_FROM_EXTRUDER)); SERIAL_ECHOLNPGM(")"); } #endif feedrate_mm_m = XY_PROBE_FEEDRATE_MM_M; do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER)); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> "); #endif if (DEPLOY_PROBE()) return NAN; float measured_z = run_z_probe(); if (stow) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> "); #endif if (STOW_PROBE()) return NAN; } else { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> do_probe_raise"); #endif do_probe_raise(Z_PROBE_TRAVEL_HEIGHT); } if (verbose_level > 2) { SERIAL_PROTOCOLPGM("Bed X: "); SERIAL_PROTOCOL_F(x, 3); SERIAL_PROTOCOLPGM(" Y: "); SERIAL_PROTOCOL_F(y, 3); SERIAL_PROTOCOLPGM(" Z: "); SERIAL_PROTOCOL_F(measured_z, 3); SERIAL_EOL; } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt"); #endif feedrate_mm_m = old_feedrate_mm_m; return measured_z; } #endif // HAS_BED_PROBE #if ENABLED(AUTO_BED_LEVELING_FEATURE) #if ENABLED(AUTO_BED_LEVELING_GRID) #if DISABLED(DELTA) static void set_bed_level_equation_lsq(double* plane_equation_coefficients) { //planner.bed_level_matrix.debug("bed level before"); #if ENABLED(DEBUG_LEVELING_FEATURE) planner.bed_level_matrix.set_to_identity(); if (DEBUGGING(LEVELING)) { vector_3 uncorrected_position = planner.adjusted_position(); DEBUG_POS(">>> set_bed_level_equation_lsq", uncorrected_position); DEBUG_POS(">>> set_bed_level_equation_lsq", current_position); } #endif vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1); planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal); vector_3 corrected_position = planner.adjusted_position(); current_position[X_AXIS] = corrected_position.x; current_position[Y_AXIS] = corrected_position.y; current_position[Z_AXIS] = corrected_position.z; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("<<< set_bed_level_equation_lsq", corrected_position); #endif SYNC_PLAN_POSITION_KINEMATIC(); } #endif // !DELTA #else // !AUTO_BED_LEVELING_GRID static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) { planner.bed_level_matrix.set_to_identity(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { vector_3 uncorrected_position = planner.adjusted_position(); DEBUG_POS("set_bed_level_equation_3pts", uncorrected_position); } #endif vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1); vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2); vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3); vector_3 planeNormal = vector_3::cross(pt1 - pt2, pt3 - pt2).get_normal(); if (planeNormal.z < 0) { planeNormal.x = -planeNormal.x; planeNormal.y = -planeNormal.y; planeNormal.z = -planeNormal.z; } planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal); vector_3 corrected_position = planner.adjusted_position(); current_position[X_AXIS] = corrected_position.x; current_position[Y_AXIS] = corrected_position.y; current_position[Z_AXIS] = corrected_position.z; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("set_bed_level_equation_3pts", corrected_position); #endif SYNC_PLAN_POSITION_KINEMATIC(); } #endif // !AUTO_BED_LEVELING_GRID #if ENABLED(DELTA) /** * All DELTA leveling in the Marlin uses NONLINEAR_BED_LEVELING */ static void extrapolate_one_point(int x, int y, int xdir, int ydir) { if (bed_level[x][y] != 0.0) { return; // Don't overwrite good values. } float a = 2 * bed_level[x + xdir][y] - bed_level[x + xdir * 2][y]; // Left to right. float b = 2 * bed_level[x][y + ydir] - bed_level[x][y + ydir * 2]; // Front to back. float c = 2 * bed_level[x + xdir][y + ydir] - bed_level[x + xdir * 2][y + ydir * 2]; // Diagonal. float median = c; // Median is robust (ignores outliers). if (a < b) { if (b < c) median = b; if (c < a) median = a; } else { // b <= a if (c < b) median = b; if (a < c) median = a; } bed_level[x][y] = median; } /** * Fill in the unprobed points (corners of circular print surface) * using linear extrapolation, away from the center. */ static void extrapolate_unprobed_bed_level() { int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2; for (int y = 0; y <= half; y++) { for (int x = 0; x <= half; x++) { if (x + y < 3) continue; extrapolate_one_point(half - x, half - y, x > 1 ? +1 : 0, y > 1 ? +1 : 0); extrapolate_one_point(half + x, half - y, x > 1 ? -1 : 0, y > 1 ? +1 : 0); extrapolate_one_point(half - x, half + y, x > 1 ? +1 : 0, y > 1 ? -1 : 0); extrapolate_one_point(half + x, half + y, x > 1 ? -1 : 0, y > 1 ? -1 : 0); } } } /** * Print calibration results for plotting or manual frame adjustment. */ static void print_bed_level() { for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) { for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) { SERIAL_PROTOCOL_F(bed_level[x][y], 2); SERIAL_PROTOCOLCHAR(' '); } SERIAL_EOL; } } /** * Reset calibration results to zero. */ void reset_bed_level() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level"); #endif for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) { for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) { bed_level[x][y] = 0.0; } } } #endif // DELTA #endif // AUTO_BED_LEVELING_FEATURE #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS) static void homeaxis(AxisEnum axis) { #define HOMEAXIS_DO(LETTER) \ ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1)) if (!(axis == X_AXIS ? HOMEAXIS_DO(X) : axis == Y_AXIS ? HOMEAXIS_DO(Y) : axis == Z_AXIS ? HOMEAXIS_DO(Z) : 0)) return; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> homeaxis(", axis); SERIAL_ECHOLNPGM(")"); } #endif int axis_home_dir = #if ENABLED(DUAL_X_CARRIAGE) (axis == X_AXIS) ? x_home_dir(active_extruder) : #endif home_dir(axis); // Homing Z towards the bed? Deploy the Z probe or endstop. #if HAS_BED_PROBE && DISABLED(Z_MIN_PROBE_ENDSTOP) if (axis == Z_AXIS && axis_home_dir < 0) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> "); #endif if (DEPLOY_PROBE()) return; } #endif // Set the axis position as setup for the move current_position[axis] = 0; sync_plan_position(); // Set a flag for Z motor locking #if ENABLED(Z_DUAL_ENDSTOPS) if (axis == Z_AXIS) stepper.set_homing_flag(true); #endif // Move towards the endstop until an endstop is triggered line_to_axis_pos(axis, 1.5 * max_length(axis) * axis_home_dir); // Set the axis position as setup for the move current_position[axis] = 0; sync_plan_position(); // Move away from the endstop by the axis HOME_BUMP_MM line_to_axis_pos(axis, -home_bump_mm(axis) * axis_home_dir); // Move slowly towards the endstop until triggered line_to_axis_pos(axis, 2 * home_bump_mm(axis) * axis_home_dir, get_homing_bump_feedrate(axis)); // reset current_position to 0 to reflect hitting endpoint current_position[axis] = 0; sync_plan_position(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> TRIGGER ENDSTOP", current_position); #endif #if ENABLED(Z_DUAL_ENDSTOPS) if (axis == Z_AXIS) { float adj = fabs(z_endstop_adj); bool lockZ1; if (axis_home_dir > 0) { adj = -adj; lockZ1 = (z_endstop_adj > 0); } else lockZ1 = (z_endstop_adj < 0); if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true); // Move to the adjusted endstop height line_to_axis_pos(axis, adj); if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false); stepper.set_homing_flag(false); } // Z_AXIS #endif #if ENABLED(DELTA) // retrace by the amount specified in endstop_adj if (endstop_adj[axis] * axis_home_dir < 0) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("> endstop_adj = ", endstop_adj[axis]); DEBUG_POS("", current_position); } #endif line_to_axis_pos(axis, endstop_adj[axis]); } #endif // Set the axis position to its home position (plus home offsets) set_axis_is_at_home(axis); SYNC_PLAN_POSITION_KINEMATIC(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position); #endif destination[axis] = current_position[axis]; endstops.hit_on_purpose(); // clear endstop hit flags axis_known_position[axis] = true; axis_homed[axis] = true; // Put away the Z probe #if HAS_BED_PROBE && DISABLED(Z_MIN_PROBE_ENDSTOP) if (axis == Z_AXIS && axis_home_dir < 0) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> "); #endif if (STOW_PROBE()) return; } #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("<<< homeaxis(", axis); SERIAL_ECHOLNPGM(")"); } #endif } #if ENABLED(FWRETRACT) void retract(bool retracting, bool swapping = false) { if (retracting == retracted[active_extruder]) return; float old_feedrate_mm_m = feedrate_mm_m; set_destination_to_current(); if (retracting) { feedrate_mm_m = MMS_TO_MMM(retract_feedrate_mm_s); current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder]; sync_plan_position_e(); prepare_move_to_destination(); if (retract_zlift > 0.01) { current_position[Z_AXIS] -= retract_zlift; SYNC_PLAN_POSITION_KINEMATIC(); prepare_move_to_destination(); } } else { if (retract_zlift > 0.01) { current_position[Z_AXIS] += retract_zlift; SYNC_PLAN_POSITION_KINEMATIC(); } feedrate_mm_m = MMS_TO_MMM(retract_recover_feedrate_mm_s); float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length; current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder]; sync_plan_position_e(); prepare_move_to_destination(); } feedrate_mm_m = old_feedrate_mm_m; retracted[active_extruder] = retracting; } // retract() #endif // FWRETRACT /** * *************************************************************************** * ***************************** G-CODE HANDLING ***************************** * *************************************************************************** */ /** * Set XYZE destination and feedrate from the current GCode command * * - Set destination from included axis codes * - Set to current for missing axis codes * - Set the feedrate, if included */ void gcode_get_destination() { LOOP_XYZE(i) { if (code_seen(axis_codes[i])) destination[i] = code_value_axis_units(i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0); else destination[i] = current_position[i]; } if (code_seen('F') && code_value_linear_units() > 0.0) feedrate_mm_m = code_value_linear_units(); #if ENABLED(PRINTCOUNTER) //淇濈暀鐩稿叧鏁版嵁 if (!DEBUGGING(DRYRUN)) print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]); #endif } void unknown_command_error() { SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND); SERIAL_ECHO(current_command); SERIAL_ECHOLNPGM("\""); } #if ENABLED(HOST_KEEPALIVE_FEATURE) /** * Output a "busy" message at regular intervals * while the machine is not accepting commands. */ void host_keepalive() { millis_t ms = millis(); if (host_keepalive_interval && busy_state != NOT_BUSY) { if (PENDING(ms, next_busy_signal_ms)) return; switch (busy_state) { case IN_HANDLER: case IN_PROCESS: SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING); break; case PAUSED_FOR_USER: SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER); break; case PAUSED_FOR_INPUT: SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT); break; default: break; } } next_busy_signal_ms = ms + host_keepalive_interval * 1000UL; } #endif //HOST_KEEPALIVE_FEATURE inline void gcode_G0_G1() { if (IsRunning()) { gcode_get_destination(); // For X Y Z E F #if ENABLED(FWRETRACT) //鏈娇鐢� if (autoretract_enabled && !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) { float echange = destination[E_AXIS] - current_position[E_AXIS]; // Is this move an attempt to retract or recover? if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) { current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations sync_plan_position_e(); // AND from the planner retract(!retracted[active_extruder]); return; } } #endif //FWRETRACT prepare_move_to_destination(); } } /** * G2: Clockwise Arc * G3: Counterclockwise Arc */ #if ENABLED(ARC_SUPPORT) inline void gcode_G2_G3(bool clockwise) { if (IsRunning()) { #if ENABLED(SF_ARC_FIX) bool relative_mode_backup = relative_mode; relative_mode = true; #endif gcode_get_destination(); #if ENABLED(SF_ARC_FIX) relative_mode = relative_mode_backup; #endif // Center of arc as offset from current_position float arc_offset[2] = { code_seen('I') ? code_value_axis_units(X_AXIS) : 0, code_seen('J') ? code_value_axis_units(Y_AXIS) : 0 }; // Send an arc to the planner plan_arc(destination, arc_offset, clockwise); refresh_cmd_timeout(); } } #endif /** * G4: Dwell S<seconds> or P<milliseconds> */ inline void gcode_G4() { millis_t dwell_ms = 0; if (code_seen('P')) dwell_ms = code_value_millis(); // milliseconds to wait if (code_seen('S')) dwell_ms = code_value_millis_from_seconds(); // seconds to wait stepper.synchronize(); refresh_cmd_timeout(); dwell_ms += previous_cmd_ms; // keep track of when we started waiting if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL); while (PENDING(millis(), dwell_ms)) idle(); } #if ENABLED(BEZIER_CURVE_SUPPORT) /** * Parameters interpreted according to: * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline * However I, J omission is not supported at this point; all * parameters can be omitted and default to zero. */ /** * G5: Cubic B-spline */ inline void gcode_G5() { if (IsRunning()) { gcode_get_destination(); float offset[] = { code_seen('I') ? code_value_axis_units(X_AXIS) : 0.0, code_seen('J') ? code_value_axis_units(Y_AXIS) : 0.0, code_seen('P') ? code_value_axis_units(X_AXIS) : 0.0, code_seen('Q') ? code_value_axis_units(Y_AXIS) : 0.0 }; plan_cubic_move(offset); } } #endif // BEZIER_CURVE_SUPPORT #if ENABLED(FWRETRACT) /** * G10 - Retract filament according to settings of M207 * G11 - Recover filament according to settings of M208 */ inline void gcode_G10_G11(bool doRetract=false) { #if EXTRUDERS > 1 if (doRetract) { retracted_swap[active_extruder] = (code_seen('S') && code_value_bool()); // checks for swap retract argument } #endif retract(doRetract #if EXTRUDERS > 1 , retracted_swap[active_extruder] #endif ); } #endif //FWRETRACT #if ENABLED(NOZZLE_CLEAN_FEATURE) /** * G12: Clean the nozzle */ inline void gcode_G12() { // Don't allow nozzle cleaning without homing first if (axis_unhomed_error(true, true, true)) { return; } uint8_t const pattern = code_seen('P') ? code_value_ushort() : 0; uint8_t const strokes = code_seen('S') ? code_value_ushort() : NOZZLE_CLEAN_STROKES; uint8_t const objects = code_seen('T') ? code_value_ushort() : 3; Nozzle::clean(pattern, strokes, objects); } #endif #if ENABLED(INCH_MODE_SUPPORT) /** * G20: Set input mode to inches */ inline void gcode_G20() { set_input_linear_units(LINEARUNIT_INCH); } /** * G21: Set input mode to millimeters */ inline void gcode_G21() { set_input_linear_units(LINEARUNIT_MM); } #endif #if ENABLED(NOZZLE_PARK_FEATURE) /** * G27: Park the nozzle */ inline void gcode_G27() { // Don't allow nozzle parking without homing first if (axis_unhomed_error(true, true, true)) { return; } uint8_t const z_action = code_seen('P') ? code_value_ushort() : 0; Nozzle::park(z_action); } #endif // NOZZLE_PARK_FEATURE #if ENABLED(QUICK_HOME) static void quick_home_xy() { // Pretend the current position is 0,0 current_position[X_AXIS] = current_position[Y_AXIS] = 0.0; sync_plan_position(); int x_axis_home_dir = #if ENABLED(DUAL_X_CARRIAGE) x_home_dir(active_extruder) #else home_dir(X_AXIS) #endif ; float mlx = max_length(X_AXIS), mly = max_length(Y_AXIS), mlratio = mlx > mly ? mly / mlx : mlx / mly, fr_mm_m = min(homing_feedrate_mm_m[X_AXIS], homing_feedrate_mm_m[Y_AXIS]) * sqrt(sq(mlratio) + 1.0); do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_m); endstops.hit_on_purpose(); // clear endstop hit flags current_position[X_AXIS] = current_position[Y_AXIS] = 0.0; } #endif // QUICK_HOME /** * G28: Home all axes according to settings * * Parameters * * None Home to all axes with no parameters. * With QUICK_HOME enabled XY will home together, then Z. * * Cartesian parameters * * X Home to the X endstop * Y Home to the Y endstop * Z Home to the Z endstop * */ inline void gcode_G28() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(">>> gcode_G28"); #endif // Wait for planner moves to finish! stepper.synchronize(); // For auto bed leveling, clear the level matrix #if ENABLED(AUTO_BED_LEVELING_FEATURE) planner.bed_level_matrix.set_to_identity(); #if ENABLED(DELTA) reset_bed_level(); #endif #endif // Always home with tool 0 active #if HOTENDS > 1 uint8_t old_tool_index = active_extruder; tool_change(0, 0, true); #endif #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE) extruder_duplication_enabled = false; #endif /** * For mesh bed leveling deactivate the mesh calculations, will be turned * on again when homing all axis */ #if ENABLED(MESH_BED_LEVELING) float pre_home_z = MESH_HOME_SEARCH_Z; if (mbl.active()) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("MBL was active"); #endif // Save known Z position if already homed if (axis_homed[X_AXIS] && axis_homed[Y_AXIS] && axis_homed[Z_AXIS]) { pre_home_z = current_position[Z_AXIS]; pre_home_z += mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS)); } mbl.set_active(false); current_position[Z_AXIS] = pre_home_z; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("Set Z to pre_home_z", current_position); #endif } #endif setup_for_endstop_or_probe_move(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)"); #endif endstops.enable(true); // Enable endstops for next homing move #if ENABLED(DELTA) /** * A delta can only safely home all axes at the same time */ // Pretend the current position is 0,0,0 // This is like quick_home_xy() but for 3 towers. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = 0.0; sync_plan_position(); // Move all carriages up together until the first endstop is hit. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = 3.0 * (Z_MAX_LENGTH); feedrate_mm_m = 1.732 * homing_feedrate_mm_m[X_AXIS]; line_to_current_position(); stepper.synchronize(); endstops.hit_on_purpose(); // clear endstop hit flags current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = 0.0; // take care of back off and rehome. Now one carriage is at the top. HOMEAXIS(X); HOMEAXIS(Y); HOMEAXIS(Z); SYNC_PLAN_POSITION_KINEMATIC(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("(DELTA)", current_position); #endif #else // NOT DELTA bool homeX = code_seen('X'), homeY = code_seen('Y'), homeZ = code_seen('Z'); home_all_axis = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ); set_destination_to_current(); #if Z_HOME_DIR > 0 // If homing away from BED do Z first if (home_all_axis || homeZ) { HOMEAXIS(Z); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position); #endif } #else if (home_all_axis || homeX || homeY) { // Raise Z before homing any other axes and z is not already high enough (never lower z) destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT); if (destination[Z_AXIS] > current_position[Z_AXIS]) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("Raise Z (before homing) to ", destination[Z_AXIS]); SERIAL_EOL; } #endif do_blocking_move_to_z(destination[Z_AXIS]); } } #endif #if ENABLED(QUICK_HOME) if (home_all_axis || (homeX && homeY)) quick_home_xy(); #endif #if ENABLED(HOME_Y_BEFORE_X) // Home Y if (home_all_axis || homeY) { HOMEAXIS(Y); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position); #endif } #endif // Home X if (home_all_axis || homeX) { #if ENABLED(DUAL_X_CARRIAGE) int tmp_extruder = active_extruder; active_extruder = !active_extruder; HOMEAXIS(X); inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]); active_extruder = tmp_extruder; HOMEAXIS(X); // reset state used by the different modes memcpy(raised_parked_position, current_position, sizeof(raised_parked_position)); delayed_move_time = 0; active_extruder_parked = true; #else HOMEAXIS(X); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position); #endif } #if DISABLED(HOME_Y_BEFORE_X) // Home Y if (home_all_axis || homeY) { HOMEAXIS(Y); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position); #endif } #endif // Home Z last if homing towards the bed #if Z_HOME_DIR < 0 if (home_all_axis || homeZ) { #if ENABLED(Z_SAFE_HOMING) #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("> Z_SAFE_HOMING >>>"); } #endif if (home_all_axis) { /** * At this point we already have Z at Z_HOMING_HEIGHT height * No need to move Z any more as this height should already be safe * enough to reach Z_SAFE_HOMING XY positions. * Just make sure the planner is in sync. */ SYNC_PLAN_POSITION_KINEMATIC(); /** * Move the Z probe (or just the nozzle) to the safe homing point */ destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - (X_PROBE_OFFSET_FROM_EXTRUDER)); destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - (Y_PROBE_OFFSET_FROM_EXTRUDER)); destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { DEBUG_POS("> Z_SAFE_HOMING > home_all_axis", current_position); DEBUG_POS("> Z_SAFE_HOMING > home_all_axis", destination); } #endif // Move in the XY plane do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]); } // Let's see if X and Y are homed if (axis_unhomed_error(true, true, false)) return; /** * Make sure the Z probe is within the physical limits * NOTE: This doesn't necessarily ensure the Z probe is also * within the bed! */ float cpx = RAW_CURRENT_POSITION(X_AXIS), cpy = RAW_CURRENT_POSITION(Y_AXIS); if ( cpx >= X_MIN_POS - (X_PROBE_OFFSET_FROM_EXTRUDER) && cpx <= X_MAX_POS - (X_PROBE_OFFSET_FROM_EXTRUDER) && cpy >= Y_MIN_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER) && cpy <= Y_MAX_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)) { // Home the Z axis HOMEAXIS(Z); } else { LCD_MESSAGEPGM(MSG_ZPROBE_OUT); SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT); } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING"); } #endif #else // !Z_SAFE_HOMING HOMEAXIS(Z); #endif // !Z_SAFE_HOMING #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all_axis || homeZ) > final", current_position); #endif } // home_all_axis || homeZ #endif // Z_HOME_DIR < 0 SYNC_PLAN_POSITION_KINEMATIC(); #endif // !DELTA (gcode_G28) #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.not_homing()"); #endif endstops.not_homing(); endstops.hit_on_purpose(); // clear endstop hit flags // Enable mesh leveling again #if ENABLED(MESH_BED_LEVELING) if (mbl.has_mesh()) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("MBL has mesh"); #endif if (home_all_axis || (axis_homed[X_AXIS] && axis_homed[Y_AXIS] && homeZ)) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("MBL Z homing"); #endif current_position[Z_AXIS] = MESH_HOME_SEARCH_Z #if Z_HOME_DIR > 0 + Z_MAX_POS #endif ; SYNC_PLAN_POSITION_KINEMATIC(); mbl.set_active(true); #if ENABLED(MESH_G28_REST_ORIGIN) current_position[Z_AXIS] = 0.0; set_destination_to_current(); feedrate_mm_m = homing_feedrate_mm_m[Z_AXIS]; line_to_destination(); stepper.synchronize(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("MBL Rest Origin", current_position); #endif #else current_position[Z_AXIS] = MESH_HOME_SEARCH_Z - mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS)) #if Z_HOME_DIR > 0 + Z_MAX_POS #endif ; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("MBL adjusted MESH_HOME_SEARCH_Z", current_position); #endif #endif } else if ((axis_homed[X_AXIS] && axis_homed[Y_AXIS] && axis_homed[Z_AXIS]) && (homeX || homeY)) { current_position[Z_AXIS] = pre_home_z; SYNC_PLAN_POSITION_KINEMATIC(); mbl.set_active(true); current_position[Z_AXIS] = pre_home_z - mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS)); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("MBL Home X or Y", current_position); #endif } } #endif #if ENABLED(DELTA) // move to a height where we can use the full xy-area do_blocking_move_to_z(delta_clip_start_height); #endif clean_up_after_endstop_or_probe_move(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28"); #endif // Restore the active tool after homing #if HOTENDS > 1 tool_change(old_tool_index, 0, true); #endif report_current_position(); } #if HAS_PROBING_PROCEDURE void out_of_range_error(const char* p_edge) { SERIAL_PROTOCOLPGM("?Probe "); serialprintPGM(p_edge); SERIAL_PROTOCOLLNPGM(" position out of range."); } #endif #if ENABLED(MESH_BED_LEVELING) inline void _mbl_goto_xy(float x, float y) { float old_feedrate_mm_m = feedrate_mm_m; feedrate_mm_m = homing_feedrate_mm_m[X_AXIS]; current_position[Z_AXIS] = MESH_HOME_SEARCH_Z #if Z_PROBE_TRAVEL_HEIGHT > Z_HOMING_HEIGHT + Z_PROBE_TRAVEL_HEIGHT #elif Z_HOMING_HEIGHT > 0 + Z_HOMING_HEIGHT #endif ; line_to_current_position(); current_position[X_AXIS] = LOGICAL_X_POSITION(x); current_position[Y_AXIS] = LOGICAL_Y_POSITION(y); line_to_current_position(); #if Z_PROBE_TRAVEL_HEIGHT > 0 || Z_HOMING_HEIGHT > 0 current_position[Z_AXIS] = LOGICAL_Z_POSITION(MESH_HOME_SEARCH_Z); line_to_current_position(); #endif feedrate_mm_m = old_feedrate_mm_m; stepper.synchronize(); } /** * G29: Mesh-based Z probe, probes a grid and produces a * mesh to compensate for variable bed height * * Parameters With MESH_BED_LEVELING: * * S0 Produce a mesh report * S1 Start probing mesh points * S2 Probe the next mesh point * S3 Xn Yn Zn.nn Manually modify a single point * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed. * S5 Reset and disable mesh * * The S0 report the points as below * * +----> X-axis 1-n * | * | * v Y-axis 1-n * */ inline void gcode_G29() { static int probe_point = -1; MeshLevelingState state = code_seen('S') ? (MeshLevelingState)code_value_byte() : MeshReport; if (state < 0 || state > 5) { SERIAL_PROTOCOLLNPGM("S out of range (0-5)."); return; } int8_t px, py; switch (state) { case MeshReport: if (mbl.has_mesh()) { SERIAL_PROTOCOLPAIR("State: ", mbl.active() ? "On" : "Off"); SERIAL_PROTOCOLPAIR("\nNum X,Y: ", MESH_NUM_X_POINTS); SERIAL_PROTOCOLCHAR(','); SERIAL_PROTOCOL(MESH_NUM_Y_POINTS); SERIAL_PROTOCOLPAIR("\nZ search height: ", MESH_HOME_SEARCH_Z); SERIAL_PROTOCOLPGM("\nZ offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5); SERIAL_PROTOCOLLNPGM("\nMeasured points:"); for (py = 0; py < MESH_NUM_Y_POINTS; py++) { for (px = 0; px < MESH_NUM_X_POINTS; px++) { SERIAL_PROTOCOLPGM(" "); SERIAL_PROTOCOL_F(mbl.z_values[py][px], 5); } SERIAL_EOL; } } else SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active."); break; case MeshStart: mbl.reset(); probe_point = 0; enqueue_and_echo_commands_P(PSTR("G28\nG29 S2")); break; case MeshNext: if (probe_point < 0) { SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first."); return; } // For each G29 S2... if (probe_point == 0) { // For the initial G29 S2 make Z a positive value (e.g., 4.0) current_position[Z_AXIS] = MESH_HOME_SEARCH_Z #if Z_HOME_DIR > 0 + Z_MAX_POS #endif ; SYNC_PLAN_POSITION_KINEMATIC(); } else { // For G29 S2 after adjusting Z. mbl.set_zigzag_z(probe_point - 1, current_position[Z_AXIS]); } // If there's another point to sample, move there with optional lift. if (probe_point < (MESH_NUM_X_POINTS) * (MESH_NUM_Y_POINTS)) { mbl.zigzag(probe_point, px, py); _mbl_goto_xy(mbl.get_probe_x(px), mbl.get_probe_y(py)); probe_point++; } else { // One last "return to the bed" (as originally coded) at completion current_position[Z_AXIS] = MESH_HOME_SEARCH_Z #if Z_PROBE_TRAVEL_HEIGHT > Z_HOMING_HEIGHT + Z_PROBE_TRAVEL_HEIGHT #elif Z_HOMING_HEIGHT > 0 + Z_HOMING_HEIGHT #endif ; line_to_current_position(); stepper.synchronize(); // After recording the last point, activate the mbl and home SERIAL_PROTOCOLLNPGM("Mesh probing done."); probe_point = -1; mbl.set_has_mesh(true); enqueue_and_echo_commands_P(PSTR("G28")); } break; case MeshSet: if (code_seen('X')) { px = code_value_int() - 1; if (px < 0 || px >= MESH_NUM_X_POINTS) { SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ")."); return; } } else { SERIAL_PROTOCOLLNPGM("X not entered."); return; } if (code_seen('Y')) { py = code_value_int() - 1; if (py < 0 || py >= MESH_NUM_Y_POINTS) { SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ")."); return; } } else { SERIAL_PROTOCOLLNPGM("Y not entered."); return; } if (code_seen('Z')) { mbl.z_values[py][px] = code_value_axis_units(Z_AXIS); } else { SERIAL_PROTOCOLLNPGM("Z not entered."); return; } break; case MeshSetZOffset: if (code_seen('Z')) { mbl.z_offset = code_value_axis_units(Z_AXIS); } else { SERIAL_PROTOCOLLNPGM("Z not entered."); return; } break; case MeshReset: if (mbl.active()) { current_position[Z_AXIS] += mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS)) - MESH_HOME_SEARCH_Z; mbl.reset(); SYNC_PLAN_POSITION_KINEMATIC(); } else mbl.reset(); } // switch(state) report_current_position(); } #elif ENABLED(AUTO_BED_LEVELING_FEATURE) /** * G29: Detailed Z probe, probes the bed at 3 or more points. * Will fail if the printer has not been homed with G28. * * Enhanced G29 Auto Bed Leveling Probe Routine * * Parameters With AUTO_BED_LEVELING_GRID: * * P Set the size of the grid that will be probed (P x P points). * Not supported by non-linear delta printer bed leveling. * Example: "G29 P4" * * S Set the XY travel speed between probe points (in units/min) * * D Dry-Run mode. Just evaluate the bed Topology - Don't apply * or clean the rotation Matrix. Useful to check the topology * after a first run of G29. * * V Set the verbose level (0-4). Example: "G29 V3" * * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report. * This is useful for manual bed leveling and finding flaws in the bed (to * assist with part placement). * Not supported by non-linear delta printer bed leveling. * * F Set the Front limit of the probing grid * B Set the Back limit of the probing grid * L Set the Left limit of the probing grid * R Set the Right limit of the probing grid * * Global Parameters: * * E/e By default G29 will engage the Z probe, test the bed, then disengage. * Include "E" to engage/disengage the Z probe for each sample. * There's no extra effect if you have a fixed Z probe. * Usage: "G29 E" or "G29 e" * */ inline void gcode_G29() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM(">>> gcode_G29"); DEBUG_POS("", current_position); } #endif // Don't allow auto-leveling without homing first if (axis_unhomed_error(true, true, true)) return; int verbose_level = code_seen('V') ? code_value_int() : 1; if (verbose_level < 0 || verbose_level > 4) { SERIAL_ECHOLNPGM("?(V)erbose Level is implausible (0-4)."); return; } bool dryrun = code_seen('D'); bool stow_probe_after_each = code_seen('E'); #if ENABLED(AUTO_BED_LEVELING_GRID) #if DISABLED(DELTA) bool do_topography_map = verbose_level > 2 || code_seen('T'); #endif if (verbose_level > 0) { SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling"); if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode"); } int auto_bed_leveling_grid_points = AUTO_BED_LEVELING_GRID_POINTS; #if DISABLED(DELTA) if (code_seen('P')) auto_bed_leveling_grid_points = code_value_int(); if (auto_bed_leveling_grid_points < 2) { SERIAL_PROTOCOLLNPGM("?Number of probed (P)oints is implausible (2 minimum)."); return; } #endif xy_probe_feedrate_mm_m = code_seen('S') ? (int)code_value_linear_units() : XY_PROBE_SPEED; int left_probe_bed_position = code_seen('L') ? (int)code_value_axis_units(X_AXIS) : LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION), right_probe_bed_position = code_seen('R') ? (int)code_value_axis_units(X_AXIS) : LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION), front_probe_bed_position = code_seen('F') ? (int)code_value_axis_units(Y_AXIS) : LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION), back_probe_bed_position = code_seen('B') ? (int)code_value_axis_units(Y_AXIS) : LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION); bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X), left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE), right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X), right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE, front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y), front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE), back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y), back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE; if (left_out || right_out || front_out || back_out) { if (left_out) { out_of_range_error(PSTR("(L)eft")); left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE); } if (right_out) { out_of_range_error(PSTR("(R)ight")); right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE; } if (front_out) { out_of_range_error(PSTR("(F)ront")); front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE); } if (back_out) { out_of_range_error(PSTR("(B)ack")); back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE; } return; } #endif // AUTO_BED_LEVELING_GRID if (!dryrun) { #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(DELTA) if (DEBUGGING(LEVELING)) { vector_3 corrected_position = planner.adjusted_position(); DEBUG_POS("BEFORE matrix.set_to_identity", corrected_position); DEBUG_POS("BEFORE matrix.set_to_identity", current_position); } #endif // make sure the bed_level_rotation_matrix is identity or the planner will get it wrong planner.bed_level_matrix.set_to_identity(); #if ENABLED(DELTA) reset_bed_level(); #else //!DELTA //vector_3 corrected_position = planner.adjusted_position(); //corrected_position.debug("position before G29"); vector_3 uncorrected_position = planner.adjusted_position(); //uncorrected_position.debug("position during G29"); current_position[X_AXIS] = uncorrected_position.x; current_position[Y_AXIS] = uncorrected_position.y; current_position[Z_AXIS] = uncorrected_position.z; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("AFTER matrix.set_to_identity", uncorrected_position); #endif SYNC_PLAN_POSITION_KINEMATIC(); #endif // !DELTA } stepper.synchronize(); setup_for_endstop_or_probe_move(); // Deploy the probe. Probe will raise if needed. if (DEPLOY_PROBE()) return; bed_leveling_in_progress = true; #if ENABLED(AUTO_BED_LEVELING_GRID) // probe at the points of a lattice grid const int xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (auto_bed_leveling_grid_points - 1), yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (auto_bed_leveling_grid_points - 1); #if ENABLED(DELTA) delta_grid_spacing[0] = xGridSpacing; delta_grid_spacing[1] = yGridSpacing; float zoffset = zprobe_zoffset; if (code_seen('Z')) zoffset += code_value_axis_units(Z_AXIS); #else // !DELTA /** * solve the plane equation ax + by + d = z * A is the matrix with rows [x y 1] for all the probed points * B is the vector of the Z positions * the normal vector to the plane is formed by the coefficients of the * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0 * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z */ int abl2 = sq(auto_bed_leveling_grid_points); double eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations eqnBVector[abl2], // "B" vector of Z points mean = 0.0; int8_t indexIntoAB[auto_bed_leveling_grid_points][auto_bed_leveling_grid_points]; #endif // !DELTA int probePointCounter = 0; bool zig = (auto_bed_leveling_grid_points & 1) ? true : false; //always end at [RIGHT_PROBE_BED_POSITION, BACK_PROBE_BED_POSITION] for (int yCount = 0; yCount < auto_bed_leveling_grid_points; yCount++) { double yProbe = front_probe_bed_position + yGridSpacing * yCount; int xStart, xStop, xInc; if (zig) { xStart = 0; xStop = auto_bed_leveling_grid_points; xInc = 1; } else { xStart = auto_bed_leveling_grid_points - 1; xStop = -1; xInc = -1; } zig = !zig; for (int xCount = xStart; xCount != xStop; xCount += xInc) { double xProbe = left_probe_bed_position + xGridSpacing * xCount; #if ENABLED(DELTA) // Avoid probing the corners (outside the round or hexagon print surface) on a delta printer. float distance_from_center = HYPOT(xProbe, yProbe); if (distance_from_center > DELTA_PROBEABLE_RADIUS) continue; #endif //DELTA float measured_z = probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level); #if DISABLED(DELTA) mean += measured_z; eqnBVector[probePointCounter] = measured_z; eqnAMatrix[probePointCounter + 0 * abl2] = xProbe; eqnAMatrix[probePointCounter + 1 * abl2] = yProbe; eqnAMatrix[probePointCounter + 2 * abl2] = 1; indexIntoAB[xCount][yCount] = probePointCounter; #else bed_level[xCount][yCount] = measured_z + zoffset; #endif probePointCounter++; idle(); } //xProbe } //yProbe #else // !AUTO_BED_LEVELING_GRID #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling"); #endif // Probe at 3 arbitrary points float z_at_pt_1 = probe_pt( LOGICAL_X_POSITION(ABL_PROBE_PT_1_X), LOGICAL_Y_POSITION(ABL_PROBE_PT_1_Y), stow_probe_after_each, verbose_level), z_at_pt_2 = probe_pt( LOGICAL_X_POSITION(ABL_PROBE_PT_2_X), LOGICAL_Y_POSITION(ABL_PROBE_PT_2_Y), stow_probe_after_each, verbose_level), z_at_pt_3 = probe_pt( LOGICAL_X_POSITION(ABL_PROBE_PT_3_X), LOGICAL_Y_POSITION(ABL_PROBE_PT_3_Y), stow_probe_after_each, verbose_level); if (!dryrun) set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3); #endif // !AUTO_BED_LEVELING_GRID // Raise to _Z_PROBE_DEPLOY_HEIGHT. Stow the probe. if (STOW_PROBE()) return; // Restore state after probing clean_up_after_endstop_or_probe_move(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position); #endif // Calculate leveling, print reports, correct the position #if ENABLED(AUTO_BED_LEVELING_GRID) #if ENABLED(DELTA) if (!dryrun) extrapolate_unprobed_bed_level(); print_bed_level(); #else // !DELTA // solve lsq problem double plane_equation_coefficients[3]; qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector); mean /= abl2; if (verbose_level) { SERIAL_PROTOCOLPGM("Eqn coefficients: a: "); SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8); SERIAL_PROTOCOLPGM(" b: "); SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8); SERIAL_PROTOCOLPGM(" d: "); SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8); SERIAL_EOL; if (verbose_level > 2) { SERIAL_PROTOCOLPGM("Mean of sampled points: "); SERIAL_PROTOCOL_F(mean, 8); SERIAL_EOL; } } if (!dryrun) set_bed_level_equation_lsq(plane_equation_coefficients); // Show the Topography map if enabled if (do_topography_map) { SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n" " +--- BACK --+\n" " | |\n" " L | (+) | R\n" " E | | I\n" " F | (-) N (+) | G\n" " T | | H\n" " | (-) | T\n" " | |\n" " O-- FRONT --+\n" " (0,0)"); float min_diff = 999; for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) { for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) { int ind = indexIntoAB[xx][yy]; float diff = eqnBVector[ind] - mean; float x_tmp = eqnAMatrix[ind + 0 * abl2], y_tmp = eqnAMatrix[ind + 1 * abl2], z_tmp = 0; apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp); NOMORE(min_diff, eqnBVector[ind] - z_tmp); if (diff >= 0.0) SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment else SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOL_F(diff, 5); } // xx SERIAL_EOL; } // yy SERIAL_EOL; if (verbose_level > 3) { SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:"); for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) { for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) { int ind = indexIntoAB[xx][yy]; float x_tmp = eqnAMatrix[ind + 0 * abl2], y_tmp = eqnAMatrix[ind + 1 * abl2], z_tmp = 0; apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp); float diff = eqnBVector[ind] - z_tmp - min_diff; if (diff >= 0.0) SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment else SERIAL_PROTOCOLCHAR(' '); SERIAL_PROTOCOL_F(diff, 5); } // xx SERIAL_EOL; } // yy SERIAL_EOL; } } //do_topography_map #endif //!DELTA #endif // AUTO_BED_LEVELING_GRID #if DISABLED(DELTA) if (verbose_level > 0) planner.bed_level_matrix.debug("\n\nBed Level Correction Matrix:"); if (!dryrun) { /** * Correct the Z height difference from Z probe position and nozzle tip position. * The Z height on homing is measured by Z probe, but the Z probe is quite far * from the nozzle. When the bed is uneven, this height must be corrected. */ float x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER, y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER, z_tmp = current_position[Z_AXIS], stepper_z = stepper.get_axis_position_mm(Z_AXIS); //get the real Z (since planner.adjusted_position is now correcting the plane) #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > stepper_z = ", stepper_z); SERIAL_ECHOPAIR(" ... z_tmp = ", z_tmp); SERIAL_EOL; } #endif // Apply the correction sending the Z probe offset apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("> AFTER apply_rotation_xyz > z_tmp = ", z_tmp); SERIAL_EOL; } #endif // Adjust the current Z and send it to the planner. current_position[Z_AXIS] += z_tmp - stepper_z; SYNC_PLAN_POSITION_KINEMATIC(); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("> corrected Z in G29", current_position); #endif } #endif // !DELTA #ifdef Z_PROBE_END_SCRIPT #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPGM("Z Probe End Script: "); SERIAL_ECHOLNPGM(Z_PROBE_END_SCRIPT); } #endif enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT)); stepper.synchronize(); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29"); #endif bed_leveling_in_progress = false; report_current_position(); KEEPALIVE_STATE(IN_HANDLER); } #endif //AUTO_BED_LEVELING_FEATURE #if HAS_BED_PROBE /** * G30: Do a single Z probe at the current XY */ inline void gcode_G30() { setup_for_endstop_or_probe_move(); // TODO: clear the leveling matrix or the planner will be set incorrectly float measured_z = probe_pt(current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER, current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER, true, 1); SERIAL_PROTOCOLPGM("Bed X: "); SERIAL_PROTOCOL(current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER + 0.0001); SERIAL_PROTOCOLPGM(" Y: "); SERIAL_PROTOCOL(current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER + 0.0001); SERIAL_PROTOCOLPGM(" Z: "); SERIAL_PROTOCOL(measured_z + 0.0001); SERIAL_EOL; clean_up_after_endstop_or_probe_move(); report_current_position(); } #if ENABLED(Z_PROBE_SLED) /** * G31: Deploy the Z probe */ inline void gcode_G31() { DEPLOY_PROBE(); } /** * G32: Stow the Z probe */ inline void gcode_G32() { STOW_PROBE(); } #endif // Z_PROBE_SLED #endif // HAS_BED_PROBE /** * G92: Set current position to given X Y Z E */ inline void gcode_G92() { bool didE = code_seen('E'); if (!didE) stepper.synchronize(); bool didXYZ = false; LOOP_XYZE(i) { if (code_seen(axis_codes[i])) { float p = current_position[i], v = code_value_axis_units(i); current_position[i] = v; if (i != E_AXIS) { position_shift[i] += v - p; // Offset the coordinate space update_software_endstops((AxisEnum)i); didXYZ = true; } } } if (didXYZ) SYNC_PLAN_POSITION_KINEMATIC(); else if (didE) sync_plan_position_e(); } #if ENABLED(ULTIPANEL) /** * M0: Unconditional stop - Wait for user button press on LCD * M1: Conditional stop - Wait for user button press on LCD */ inline void gcode_M0_M1() { char* args = current_command_args; millis_t codenum = 0; bool hasP = false, hasS = false; if (code_seen('P')) { codenum = code_value_millis(); // milliseconds to wait hasP = codenum > 0; } if (code_seen('S')) { codenum = code_value_millis_from_seconds(); // seconds to wait hasS = codenum > 0; } if (!hasP && !hasS && *args != '\0') lcd_setstatus(args, true); else { LCD_MESSAGEPGM(MSG_USERWAIT); #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0 dontExpireStatus(); #endif } lcd_ignore_click(); stepper.synchronize(); refresh_cmd_timeout(); if (codenum > 0) { codenum += previous_cmd_ms; // wait until this time for a click KEEPALIVE_STATE(PAUSED_FOR_USER); while (PENDING(millis(), codenum) && !lcd_clicked()) idle(); KEEPALIVE_STATE(IN_HANDLER); lcd_ignore_click(false); } else { if (!lcd_detected()) return; KEEPALIVE_STATE(PAUSED_FOR_USER); while (!lcd_clicked()) idle(); KEEPALIVE_STATE(IN_HANDLER); } if (IS_SD_PRINTING) LCD_MESSAGEPGM(MSG_RESUMING); else LCD_MESSAGEPGM(WELCOME_MSG); } #endif // ULTIPANEL /** * M17: Enable power on all stepper motors */ inline void gcode_M17() { LCD_MESSAGEPGM(MSG_NO_MOVE); enable_all_steppers(); } #if ENABLED(SDSUPPORT) /** * M20: List SD card to serial output */ inline void gcode_M20() { SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST); card.ls(); SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST); } /** * M21: Init SD Card */ inline void gcode_M21() { card.initsd(); } /** * M22: Release SD Card */ inline void gcode_M22() { card.release(); } /** * M23: Open a file */ inline void gcode_M23() { card.openFile(current_command_args, true); } /** * M24: Start SD Print */ inline void gcode_M24() { card.startFileprint(); print_job_timer.start(); } /** * M25: Pause SD Print */ inline void gcode_M25() { card.pauseSDPrint(); } /** * M26: Set SD Card file index */ inline void gcode_M26() { if (card.cardOK && code_seen('S')) card.setIndex(code_value_long()); } /** * M27: Get SD Card status */ inline void gcode_M27() { card.getStatus(); } /** * M28: Start SD Write */ inline void gcode_M28() { card.openFile(current_command_args, false); } /** * M29: Stop SD Write * Processed in write to file routine above */ inline void gcode_M29() { // card.saving = false; } /** * M30 <filename>: Delete SD Card file */ inline void gcode_M30() { if (card.cardOK) { card.closefile(); card.removeFile(current_command_args); } } #endif //SDSUPPORT /** * M31: Get the time since the start of SD Print (or last M109) */ inline void gcode_M31() { char buffer[21]; duration_t elapsed = print_job_timer.duration(); elapsed.toString(buffer); lcd_setstatus(buffer); SERIAL_ECHO_START; SERIAL_ECHOPGM("Print time: "); SERIAL_ECHOLN(buffer); thermalManager.autotempShutdown(); } #if ENABLED(SDSUPPORT) /** * M32: Select file and start SD Print */ inline void gcode_M32() { if (card.sdprinting) stepper.synchronize(); char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start. if (!namestartpos) namestartpos = current_command_args; // Default name position, 4 letters after the M else namestartpos++; //to skip the '!' bool call_procedure = code_seen('P') && (seen_pointer < namestartpos); if (card.cardOK) { card.openFile(namestartpos, true, call_procedure); if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!) card.setIndex(code_value_long()); card.startFileprint(); // Procedure calls count as normal print time. if (!call_procedure) print_job_timer.start(); } } #if ENABLED(LONG_FILENAME_HOST_SUPPORT) /** * M33: Get the long full path of a file or folder * * Parameters: * <dospath> Case-insensitive DOS-style path to a file or folder * * Example: * M33 miscel~1/armchair/armcha~1.gco * * Output: * /Miscellaneous/Armchair/Armchair.gcode */ inline void gcode_M33() { card.printLongPath(current_command_args); } #endif /** * M928: Start SD Write */ inline void gcode_M928() { card.openLogFile(current_command_args); } #endif // SDSUPPORT /** * M42: Change pin status via GCode * * P<pin> Pin number (LED if omitted) * S<byte> Pin status from 0 - 255 */ inline void gcode_M42() { if (!code_seen('S')) return; int pin_status = code_value_int(); if (pin_status < 0 || pin_status > 255) return; int pin_number = code_seen('P') ? code_value_int() : LED_PIN; if (pin_number < 0) return; for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) if (pin_number == sensitive_pins[i]) return; pinMode(pin_number, OUTPUT); digitalWrite(pin_number, pin_status); analogWrite(pin_number, pin_status); #if FAN_COUNT > 0 switch (pin_number) { #if HAS_FAN0 case FAN_PIN: fanSpeeds[0] = pin_status; break; #endif #if HAS_FAN1 case FAN1_PIN: fanSpeeds[1] = pin_status; break; #endif #if HAS_FAN2 case FAN2_PIN: fanSpeeds[2] = pin_status; break; #endif } #endif } #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST) /** * M48: Z probe repeatability measurement function. * * Usage: * M48 <P#> <X#> <Y#> <V#> <E> <L#> * P = Number of sampled points (4-50, default 10) * X = Sample X position * Y = Sample Y position * V = Verbose level (0-4, default=1) * E = Engage Z probe for each reading * L = Number of legs of movement before probe * S = Schizoid (Or Star if you prefer) * * This function assumes the bed has been homed. Specifically, that a G28 command * as been issued prior to invoking the M48 Z probe repeatability measurement function. * Any information generated by a prior G29 Bed leveling command will be lost and need to be * regenerated. */ inline void gcode_M48() { if (axis_unhomed_error(true, true, true)) return; int8_t verbose_level = code_seen('V') ? code_value_byte() : 1; if (verbose_level < 0 || verbose_level > 4) { SERIAL_PROTOCOLLNPGM("?Verbose Level not plausible (0-4)."); return; } if (verbose_level > 0) SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability test"); int8_t n_samples = code_seen('P') ? code_value_byte() : 10; if (n_samples < 4 || n_samples > 50) { SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50)."); return; } float X_current = current_position[X_AXIS], Y_current = current_position[Y_AXIS]; bool stow_probe_after_each = code_seen('E'); float X_probe_location = code_seen('X') ? code_value_axis_units(X_AXIS) : X_current + X_PROBE_OFFSET_FROM_EXTRUDER; #if DISABLED(DELTA) if (X_probe_location < LOGICAL_X_POSITION(MIN_PROBE_X) || X_probe_location > LOGICAL_X_POSITION(MAX_PROBE_X)) { out_of_range_error(PSTR("X")); return; } #endif float Y_probe_location = code_seen('Y') ? code_value_axis_units(Y_AXIS) : Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER; #if DISABLED(DELTA) if (Y_probe_location < LOGICAL_Y_POSITION(MIN_PROBE_Y) || Y_probe_location > LOGICAL_Y_POSITION(MAX_PROBE_Y)) { out_of_range_error(PSTR("Y")); return; } #else if (HYPOT(RAW_X_POSITION(X_probe_location), RAW_Y_POSITION(Y_probe_location)) > DELTA_PROBEABLE_RADIUS) { SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius."); return; } #endif bool seen_L = code_seen('L'); uint8_t n_legs = seen_L ? code_value_byte() : 0; if (n_legs > 15) { SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15)."); return; } if (n_legs == 1) n_legs = 2; bool schizoid_flag = code_seen('S'); if (schizoid_flag && !seen_L) n_legs = 7; /** * Now get everything to the specified probe point So we can safely do a * probe to get us close to the bed. If the Z-Axis is far from the bed, * we don't want to use that as a starting point for each probe. */ if (verbose_level > 2) SERIAL_PROTOCOLLNPGM("Positioning the probe..."); #if ENABLED(DELTA) // we don't do bed level correction in M48 because we want the raw data when we probe reset_bed_level(); #elif ENABLED(AUTO_BED_LEVELING_FEATURE) // we don't do bed level correction in M48 because we want the raw data when we probe planner.bed_level_matrix.set_to_identity(); #endif setup_for_endstop_or_probe_move(); // Move to the first point, deploy, and probe probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level); randomSeed(millis()); double mean = 0, sigma = 0, sample_set[n_samples]; for (uint8_t n = 0; n < n_samples; n++) { if (n_legs) { int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise float angle = random(0.0, 360.0), radius = random( #if ENABLED(DELTA) DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3 #else 5, X_MAX_LENGTH / 8 #endif ); if (verbose_level > 3) { SERIAL_ECHOPAIR("Starting radius: ", radius); SERIAL_ECHOPAIR(" angle: ", angle); SERIAL_ECHOPGM(" Direction: "); if (dir > 0) SERIAL_ECHOPGM("Counter-"); SERIAL_ECHOLNPGM("Clockwise"); } for (uint8_t l = 0; l < n_legs - 1; l++) { double delta_angle; if (schizoid_flag) // The points of a 5 point star are 72 degrees apart. We need to // skip a point and go to the next one on the star. delta_angle = dir * 2.0 * 72.0; else // If we do this line, we are just trying to move further // around the circle. delta_angle = dir * (float) random(25, 45); angle += delta_angle; while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the angle -= 360.0; // Arduino documentation says the trig functions should not be given values while (angle < 0.0) // outside of this range. It looks like they behave correctly with angle += 360.0; // numbers outside of the range, but just to be safe we clamp them. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius; Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius; #if DISABLED(DELTA) X_current = constrain(X_current, X_MIN_POS, X_MAX_POS); Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS); #else // If we have gone out too far, we can do a simple fix and scale the numbers // back in closer to the origin. while (HYPOT(X_current, Y_current) > DELTA_PROBEABLE_RADIUS) { X_current /= 1.25; Y_current /= 1.25; if (verbose_level > 3) { SERIAL_ECHOPAIR("Pulling point towards center:", X_current); SERIAL_ECHOPAIR(", ", Y_current); SERIAL_EOL; } } #endif if (verbose_level > 3) { SERIAL_PROTOCOLPGM("Going to:"); SERIAL_ECHOPAIR(" X", X_current); SERIAL_ECHOPAIR(" Y", Y_current); SERIAL_ECHOPAIR(" Z", current_position[Z_AXIS]); SERIAL_EOL; } do_blocking_move_to_xy(X_current, Y_current); } // n_legs loop } // n_legs // Probe a single point sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level); /** * Get the current mean for the data points we have so far */ double sum = 0.0; for (uint8_t j = 0; j <= n; j++) sum += sample_set[j]; mean = sum / (n + 1); /** * Now, use that mean to calculate the standard deviation for the * data points we have so far */ sum = 0.0; for (uint8_t j = 0; j <= n; j++) sum += sq(sample_set[j] - mean); sigma = sqrt(sum / (n + 1)); if (verbose_level > 0) { if (verbose_level > 1) { SERIAL_PROTOCOL(n + 1); SERIAL_PROTOCOLPGM(" of "); SERIAL_PROTOCOL((int)n_samples); SERIAL_PROTOCOLPGM(" z: "); SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6); if (verbose_level > 2) { SERIAL_PROTOCOLPGM(" mean: "); SERIAL_PROTOCOL_F(mean, 6); SERIAL_PROTOCOLPGM(" sigma: "); SERIAL_PROTOCOL_F(sigma, 6); } } SERIAL_EOL; } } // End of probe loop if (STOW_PROBE()) return; if (verbose_level > 0) { SERIAL_PROTOCOLPGM("Mean: "); SERIAL_PROTOCOL_F(mean, 6); SERIAL_EOL; } SERIAL_PROTOCOLPGM("Standard Deviation: "); SERIAL_PROTOCOL_F(sigma, 6); SERIAL_EOL; SERIAL_EOL; clean_up_after_endstop_or_probe_move(); report_current_position(); } #endif // Z_MIN_PROBE_REPEATABILITY_TEST /** * M75: Start print timer */ inline void gcode_M75() { print_job_timer.start(); } /** * M76: Pause print timer */ inline void gcode_M76() { print_job_timer.pause(); } /** * M77: Stop print timer */ inline void gcode_M77() { print_job_timer.stop(); } #if ENABLED(PRINTCOUNTER) /** * M78: Show print statistics */ inline void gcode_M78() { // "M78 S78" will reset the statistics if (code_seen('S') && code_value_int() == 78) print_job_timer.initStats(); else print_job_timer.showStats(); } #endif /** * M104: Set hot end temperature */ inline void gcode_M104() { if (get_target_extruder_from_command(104)) return; if (DEBUGGING(DRYRUN)) return; #if ENABLED(SINGLENOZZLE) if (target_extruder != active_extruder) return; #endif if (code_seen('S')) { thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder); #if ENABLED(DUAL_X_CARRIAGE) if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0) thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1); #endif #if ENABLED(PRINTJOB_TIMER_AUTOSTART) /** * Stop the timer at the end of print, starting is managed by * 'heat and wait' M109. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot * stand by mode, for instance in a dual extruder setup, without affecting * the running print timer. */ if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) { print_job_timer.stop(); LCD_MESSAGEPGM(WELCOME_MSG); } #endif if (code_value_temp_abs() > thermalManager.degHotend(target_extruder)) LCD_MESSAGEPGM(MSG_HEATING); } } #if HAS_TEMP_HOTEND || HAS_TEMP_BED void print_heaterstates() { #if HAS_TEMP_HOTEND SERIAL_PROTOCOLPGM(" T:"); SERIAL_PROTOCOL_F(thermalManager.degHotend(target_extruder), 1); SERIAL_PROTOCOLPGM(" /"); SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(target_extruder), 1); #if ENABLED(SHOW_TEMP_ADC_VALUES) SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_raw[target_extruder] / OVERSAMPLENR); SERIAL_CHAR(')'); #endif #endif #if HAS_TEMP_BED SERIAL_PROTOCOLPGM(" B:"); SERIAL_PROTOCOL_F(thermalManager.degBed(), 1); SERIAL_PROTOCOLPGM(" /"); SERIAL_PROTOCOL_F(thermalManager.degTargetBed(), 1); #if ENABLED(SHOW_TEMP_ADC_VALUES) SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_bed_raw / OVERSAMPLENR); SERIAL_CHAR(')'); #endif #endif #if HOTENDS > 1 HOTEND_LOOP() { SERIAL_PROTOCOLPAIR(" T", e); SERIAL_PROTOCOLCHAR(':'); SERIAL_PROTOCOL_F(thermalManager.degHotend(e), 1); SERIAL_PROTOCOLPGM(" /"); SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(e), 1); #if ENABLED(SHOW_TEMP_ADC_VALUES) SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_raw[e] / OVERSAMPLENR); SERIAL_CHAR(')'); #endif } #endif SERIAL_PROTOCOLPGM(" @:"); SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder)); #if HAS_TEMP_BED SERIAL_PROTOCOLPGM(" B@:"); SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1)); #endif #if HOTENDS > 1 HOTEND_LOOP() { SERIAL_PROTOCOLPAIR(" @", e); SERIAL_PROTOCOLCHAR(':'); SERIAL_PROTOCOL(thermalManager.getHeaterPower(e)); } #endif } #endif /** * M105: Read hot end and bed temperature */ inline void gcode_M105() { if (get_target_extruder_from_command(105)) return; #if HAS_TEMP_HOTEND || HAS_TEMP_BED SERIAL_PROTOCOLPGM(MSG_OK); print_heaterstates(); #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS); #endif SERIAL_EOL; } #if FAN_COUNT > 0 /** * M106: Set Fan Speed * * S<int> Speed between 0-255 * P<index> Fan index, if more than one fan */ inline void gcode_M106() { uint16_t s = code_seen('S') ? code_value_ushort() : 255, p = code_seen('P') ? code_value_ushort() : 0; NOMORE(s, 255); if (p < FAN_COUNT) fanSpeeds[p] = s; } /** * M107: Fan Off */ inline void gcode_M107() { uint16_t p = code_seen('P') ? code_value_ushort() : 0; if (p < FAN_COUNT) fanSpeeds[p] = 0; } #endif // FAN_COUNT > 0 #if DISABLED(EMERGENCY_PARSER) /** * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature. */ inline void gcode_M108() { wait_for_heatup = false; } /** * M112: Emergency Stop */ inline void gcode_M112() { kill(PSTR(MSG_KILLED)); } /** * M410: Quickstop - Abort all planned moves * * This will stop the carriages mid-move, so most likely they * will be out of sync with the stepper position after this. */ inline void gcode_M410() { quickstop_stepper(); } #endif #ifndef MIN_COOLING_SLOPE_DEG #define MIN_COOLING_SLOPE_DEG 1.50 #endif #ifndef MIN_COOLING_SLOPE_TIME #define MIN_COOLING_SLOPE_TIME 60 #endif /** * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling. */ inline void gcode_M109() { if (get_target_extruder_from_command(109)) return; if (DEBUGGING(DRYRUN)) return; #if ENABLED(SINGLENOZZLE) if (target_extruder != active_extruder) return; #endif bool no_wait_for_cooling = code_seen('S'); if (no_wait_for_cooling || code_seen('R')) { thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder); #if ENABLED(DUAL_X_CARRIAGE) if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0) thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1); #endif #if ENABLED(PRINTJOB_TIMER_AUTOSTART) /** * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot * stand by mode, for instance in a dual extruder setup, without affecting * the running print timer. */ if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) { print_job_timer.stop(); LCD_MESSAGEPGM(WELCOME_MSG); } /** * We do not check if the timer is already running because this check will * be done for us inside the Stopwatch::start() method thus a running timer * will not restart. */ else print_job_timer.start(); #endif if (thermalManager.isHeatingHotend(target_extruder)) LCD_MESSAGEPGM(MSG_HEATING); } #if ENABLED(AUTOTEMP) planner.autotemp_M109(); #endif #if TEMP_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; // Loop until the temperature has stabilized #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL)) #else // Loop until the temperature is very close target #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder)) #endif //TEMP_RESIDENCY_TIME > 0 float theTarget = -1.0, old_temp = 9999.0; bool wants_to_cool = false; wait_for_heatup = true; millis_t now, next_temp_ms = 0, next_cool_check_ms = 0; KEEPALIVE_STATE(NOT_BUSY); do { // Target temperature might be changed during the loop if (theTarget != thermalManager.degTargetHotend(target_extruder)) { wants_to_cool = thermalManager.isCoolingHotend(target_extruder); theTarget = thermalManager.degTargetHotend(target_extruder); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting next_temp_ms = now + 1000UL; print_heaterstates(); #if TEMP_RESIDENCY_TIME > 0 SERIAL_PROTOCOLPGM(" W:"); if (residency_start_ms) { long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL; SERIAL_PROTOCOLLN(rem); } else { SERIAL_PROTOCOLLNPGM("?"); } #else SERIAL_EOL; #endif } idle(); refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out float temp = thermalManager.degHotend(target_extruder); #if TEMP_RESIDENCY_TIME > 0 float temp_diff = fabs(theTarget - temp); if (!residency_start_ms) { // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_WINDOW) residency_start_ms = now; } else if (temp_diff > TEMP_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } #endif //TEMP_RESIDENCY_TIME > 0 // Prevent a wait-forever situation if R is misused i.e. M109 R0 if (wants_to_cool) { // break after MIN_COOLING_SLOPE_TIME seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) { if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break; next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME; old_temp = temp; } } } while (wait_for_heatup && TEMP_CONDITIONS); LCD_MESSAGEPGM(MSG_HEATING_COMPLETE); KEEPALIVE_STATE(IN_HANDLER); } #if HAS_TEMP_BED #ifndef MIN_COOLING_SLOPE_DEG_BED #define MIN_COOLING_SLOPE_DEG_BED 1.50 #endif #ifndef MIN_COOLING_SLOPE_TIME_BED #define MIN_COOLING_SLOPE_TIME_BED 60 #endif /** * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling */ inline void gcode_M190() { if (DEBUGGING(DRYRUN)) return; LCD_MESSAGEPGM(MSG_BED_HEATING); bool no_wait_for_cooling = code_seen('S'); if (no_wait_for_cooling || code_seen('R')) { thermalManager.setTargetBed(code_value_temp_abs()); #if ENABLED(PRINTJOB_TIMER_AUTOSTART) if (code_value_temp_abs() > BED_MINTEMP) { /** * We start the timer when 'heating and waiting' command arrives, LCD * functions never wait. Cooling down managed by extruders. * * We do not check if the timer is already running because this check will * be done for us inside the Stopwatch::start() method thus a running timer * will not restart. */ print_job_timer.start(); } #endif } #if TEMP_BED_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; // Loop until the temperature has stabilized #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL)) #else // Loop until the temperature is very close target #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed()) #endif //TEMP_BED_RESIDENCY_TIME > 0 float theTarget = -1.0, old_temp = 9999.0; bool wants_to_cool = false; wait_for_heatup = true; millis_t now, next_temp_ms = 0, next_cool_check_ms = 0; KEEPALIVE_STATE(NOT_BUSY); target_extruder = active_extruder; // for print_heaterstates do { // Target temperature might be changed during the loop if (theTarget != thermalManager.degTargetBed()) { wants_to_cool = thermalManager.isCoolingBed(); theTarget = thermalManager.degTargetBed(); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up. next_temp_ms = now + 1000UL; print_heaterstates(); #if TEMP_BED_RESIDENCY_TIME > 0 SERIAL_PROTOCOLPGM(" W:"); if (residency_start_ms) { long rem = (((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL; SERIAL_PROTOCOLLN(rem); } else { SERIAL_PROTOCOLLNPGM("?"); } #else SERIAL_EOL; #endif } idle(); refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out float temp = thermalManager.degBed(); #if TEMP_BED_RESIDENCY_TIME > 0 float temp_diff = fabs(theTarget - temp); if (!residency_start_ms) { // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now; } else if (temp_diff > TEMP_BED_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } #endif //TEMP_BED_RESIDENCY_TIME > 0 // Prevent a wait-forever situation if R is misused i.e. M190 R0 if (wants_to_cool) { // break after MIN_COOLING_SLOPE_TIME_BED seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) { if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break; next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED; old_temp = temp; } } } while (wait_for_heatup && TEMP_BED_CONDITIONS); LCD_MESSAGEPGM(MSG_BED_DONE); KEEPALIVE_STATE(IN_HANDLER); } #endif // HAS_TEMP_BED /** * M110: Set Current Line Number */ inline void gcode_M110() { if (code_seen('N')) gcode_N = code_value_long(); } /** * M111: Set the debug level */ inline void gcode_M111() { marlin_debug_flags = code_seen('S') ? code_value_byte() : (uint8_t) DEBUG_NONE; const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO; const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO; const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS; const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN; const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION; #if ENABLED(DEBUG_LEVELING_FEATURE) const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING; #endif const static char* const debug_strings[] PROGMEM = { str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16, #if ENABLED(DEBUG_LEVELING_FEATURE) str_debug_32 #endif }; SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_DEBUG_PREFIX); if (marlin_debug_flags) { uint8_t comma = 0; for (uint8_t i = 0; i < COUNT(debug_strings); i++) { if (TEST(marlin_debug_flags, i)) { if (comma++) SERIAL_CHAR(','); serialprintPGM((char*)pgm_read_word(&(debug_strings[i]))); } } } else { SERIAL_ECHOPGM(MSG_DEBUG_OFF); } SERIAL_EOL; } #if ENABLED(HOST_KEEPALIVE_FEATURE) /** * M113: Get or set Host Keepalive interval (0 to disable) * * S<seconds> Optional. Set the keepalive interval. */ inline void gcode_M113() { if (code_seen('S')) { host_keepalive_interval = code_value_byte(); NOMORE(host_keepalive_interval, 60); } else { SERIAL_ECHO_START; SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval); SERIAL_EOL; } } #endif #if ENABLED(BARICUDA) #if HAS_HEATER_1 /** * M126: Heater 1 valve open */ inline void gcode_M126() { baricuda_valve_pressure = code_seen('S') ? code_value_byte() : 255; } /** * M127: Heater 1 valve close */ inline void gcode_M127() { baricuda_valve_pressure = 0; } #endif #if HAS_HEATER_2 /** * M128: Heater 2 valve open */ inline void gcode_M128() { baricuda_e_to_p_pressure = code_seen('S') ? code_value_byte() : 255; } /** * M129: Heater 2 valve close */ inline void gcode_M129() { baricuda_e_to_p_pressure = 0; } #endif #endif //BARICUDA /** * M140: Set bed temperature */ inline void gcode_M140() { if (DEBUGGING(DRYRUN)) return; if (code_seen('S')) thermalManager.setTargetBed(code_value_temp_abs()); } #if ENABLED(ULTIPANEL) /** * M145: Set the heatup state for a material in the LCD menu * S<material> (0=PLA, 1=ABS) * H<hotend temp> * B<bed temp> * F<fan speed> */ inline void gcode_M145() { int8_t material = code_seen('S') ? (int8_t)code_value_int() : 0; if (material < 0 || material > 1) { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX); } else { int v; switch (material) { case 0: if (code_seen('H')) { v = code_value_int(); preheatHotendTemp1 = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15); } if (code_seen('F')) { v = code_value_int(); preheatFanSpeed1 = constrain(v, 0, 255); } #if TEMP_SENSOR_BED != 0 if (code_seen('B')) { v = code_value_int(); preheatBedTemp1 = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15); } #endif break; case 1: if (code_seen('H')) { v = code_value_int(); preheatHotendTemp2 = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15); } if (code_seen('F')) { v = code_value_int(); preheatFanSpeed2 = constrain(v, 0, 255); } #if TEMP_SENSOR_BED != 0 if (code_seen('B')) { v = code_value_int(); preheatBedTemp2 = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15); } #endif break; } } } #endif #if ENABLED(TEMPERATURE_UNITS_SUPPORT) /** * M149: Set temperature units */ inline void gcode_M149() { if (code_seen('C')) { set_input_temp_units(TEMPUNIT_C); } else if (code_seen('K')) { set_input_temp_units(TEMPUNIT_K); } else if (code_seen('F')) { set_input_temp_units(TEMPUNIT_F); } } #endif #if HAS_POWER_SWITCH /** * M80: Turn on Power Supply */ inline void gcode_M80() { OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND /** * If you have a switch on suicide pin, this is useful * if you want to start another print with suicide feature after * a print without suicide... */ #if HAS_SUICIDE OUT_WRITE(SUICIDE_PIN, HIGH); #endif #if ENABLED(ULTIPANEL) powersupply = true; LCD_MESSAGEPGM(WELCOME_MSG); lcd_update(); #endif } #endif // HAS_POWER_SWITCH /** * M81: Turn off Power, including Power Supply, if there is one. * * This code should ALWAYS be available for EMERGENCY SHUTDOWN! */ inline void gcode_M81() { thermalManager.disable_all_heaters(); stepper.finish_and_disable(); #if FAN_COUNT > 0 #if FAN_COUNT > 1 for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0; #else fanSpeeds[0] = 0; #endif #endif delay(1000); // Wait 1 second before switching off #if HAS_SUICIDE stepper.synchronize(); suicide(); #elif HAS_POWER_SWITCH OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP); #endif #if ENABLED(ULTIPANEL) #if HAS_POWER_SWITCH powersupply = false; #endif LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF "."); lcd_update(); #endif } /** * M82: Set E codes absolute (default) */ inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; } /** * M83: Set E codes relative while in Absolute Coordinates (G90) mode */ inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; } /** * M18, M84: Disable all stepper motors */ inline void gcode_M18_M84() { if (code_seen('S')) { stepper_inactive_time = code_value_millis_from_seconds(); } else { bool all_axis = !((code_seen('X')) || (code_seen('Y')) || (code_seen('Z')) || (code_seen('E'))); if (all_axis) { stepper.finish_and_disable(); } else { stepper.synchronize(); if (code_seen('X')) disable_x(); if (code_seen('Y')) disable_y(); if (code_seen('Z')) disable_z(); #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS if (code_seen('E')) { disable_e0(); disable_e1(); disable_e2(); disable_e3(); } #endif } } } /** * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default) */ inline void gcode_M85() { if (code_seen('S')) max_inactive_time = code_value_millis_from_seconds(); } /** * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E. * (Follows the same syntax as G92) */ inline void gcode_M92() { LOOP_XYZE(i) { if (code_seen(axis_codes[i])) { if (i == E_AXIS) { float value = code_value_per_axis_unit(i); if (value < 20.0) { float factor = planner.axis_steps_per_mm[i] / value; // increase e constants if M92 E14 is given for netfab. planner.max_e_jerk *= factor; planner.max_feedrate_mm_s[i] *= factor; planner.max_acceleration_steps_per_s2[i] *= factor; } planner.axis_steps_per_mm[i] = value; } else { planner.axis_steps_per_mm[i] = code_value_per_axis_unit(i); } } } planner.refresh_positioning(); } /** * Output the current position to serial */ static void report_current_position() { SERIAL_PROTOCOLPGM("X:"); SERIAL_PROTOCOL(current_position[X_AXIS]); SERIAL_PROTOCOLPGM(" Y:"); SERIAL_PROTOCOL(current_position[Y_AXIS]); SERIAL_PROTOCOLPGM(" Z:"); SERIAL_PROTOCOL(current_position[Z_AXIS]); SERIAL_PROTOCOLPGM(" E:"); SERIAL_PROTOCOL(current_position[E_AXIS]); stepper.report_positions(); #if ENABLED(SCARA) SERIAL_PROTOCOLPGM("SCARA Theta:"); SERIAL_PROTOCOL(delta[X_AXIS]); SERIAL_PROTOCOLPGM(" Psi+Theta:"); SERIAL_PROTOCOL(delta[Y_AXIS]); SERIAL_EOL; SERIAL_PROTOCOLPGM("SCARA Cal - Theta:"); SERIAL_PROTOCOL(delta[X_AXIS]); SERIAL_PROTOCOLPGM(" Psi+Theta (90):"); SERIAL_PROTOCOL(delta[Y_AXIS] - delta[X_AXIS] - 90); SERIAL_EOL; SERIAL_PROTOCOLPGM("SCARA step Cal - Theta:"); SERIAL_PROTOCOL(delta[X_AXIS] / 90 * planner.axis_steps_per_mm[X_AXIS]); SERIAL_PROTOCOLPGM(" Psi+Theta:"); SERIAL_PROTOCOL((delta[Y_AXIS] - delta[X_AXIS]) / 90 * planner.axis_steps_per_mm[Y_AXIS]); SERIAL_EOL; SERIAL_EOL; #endif } /** * M114: Output current position to serial port */ inline void gcode_M114() { report_current_position(); } /** * M115: Capabilities string */ inline void gcode_M115() { SERIAL_PROTOCOLPGM(MSG_M115_REPORT); } /** * M117: Set LCD Status Message */ inline void gcode_M117() { lcd_setstatus(current_command_args); } /** * M119: Output endstop states to serial output */ inline void gcode_M119() { endstops.M119(); } /** * M120: Enable endstops and set non-homing endstop state to "enabled" */ inline void gcode_M120() { endstops.enable_globally(true); } /** * M121: Disable endstops and set non-homing endstop state to "disabled" */ inline void gcode_M121() { endstops.enable_globally(false); } #if ENABLED(BLINKM) /** * M150: Set Status LED Color - Use R-U-B for R-G-B */ inline void gcode_M150() { SendColors( code_seen('R') ? code_value_byte() : 0, code_seen('U') ? code_value_byte() : 0, code_seen('B') ? code_value_byte() : 0 ); } #endif // BLINKM #if ENABLED(EXPERIMENTAL_I2CBUS) /** * M155: Send data to a I2C slave device * * This is a PoC, the formating and arguments for the GCODE will * change to be more compatible, the current proposal is: * * M155 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to * * M155 B<byte-1 value in base 10> * M155 B<byte-2 value in base 10> * M155 B<byte-3 value in base 10> * * M155 S1 ; Send the buffered data and reset the buffer * M155 R1 ; Reset the buffer without sending data * */ inline void gcode_M155() { // Set the target address if (code_seen('A')) i2c.address(code_value_byte()); // Add a new byte to the buffer else if (code_seen('B')) i2c.addbyte(code_value_int()); // Flush the buffer to the bus else if (code_seen('S')) i2c.send(); // Reset and rewind the buffer else if (code_seen('R')) i2c.reset(); } /** * M156: Request X bytes from I2C slave device * * Usage: M156 A<slave device address base 10> B<number of bytes> */ inline void gcode_M156() { uint8_t addr = code_seen('A') ? code_value_byte() : 0; int bytes = code_seen('B') ? code_value_int() : 1; if (addr && bytes > 0 && bytes <= 32) { i2c.address(addr); i2c.reqbytes(bytes); } else { SERIAL_ERROR_START; SERIAL_ERRORLN("Bad i2c request"); } } #endif //EXPERIMENTAL_I2CBUS /** * M200: Set filament diameter and set E axis units to cubic units * * T<extruder> - Optional extruder number. Current extruder if omitted. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis. */ inline void gcode_M200() { if (get_target_extruder_from_command(200)) return; if (code_seen('D')) { // setting any extruder filament size disables volumetric on the assumption that // slicers either generate in extruder values as cubic mm or as as filament feeds // for all extruders volumetric_enabled = (code_value_linear_units() != 0.0); if (volumetric_enabled) { filament_size[target_extruder] = code_value_linear_units(); // make sure all extruders have some sane value for the filament size for (uint8_t i = 0; i < COUNT(filament_size); i++) if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA; } } else { //reserved for setting filament diameter via UFID or filament measuring device return; } calculate_volumetric_multipliers(); } /** * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000) */ inline void gcode_M201() { LOOP_XYZE(i) { if (code_seen(axis_codes[i])) { planner.max_acceleration_mm_per_s2[i] = code_value_axis_units(i); } } // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner) planner.reset_acceleration_rates(); } #if 0 // Not used for Sprinter/grbl gen6 inline void gcode_M202() { LOOP_XYZE(i) { if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value_axis_units(i) * planner.axis_steps_per_mm[i]; } } #endif /** * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec */ inline void gcode_M203() { LOOP_XYZE(i) if (code_seen(axis_codes[i])) planner.max_feedrate_mm_s[i] = code_value_axis_units(i); } /** * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000) * * P = Printing moves * R = Retract only (no X, Y, Z) moves * T = Travel (non printing) moves * * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate */ inline void gcode_M204() { if (code_seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments. planner.travel_acceleration = planner.acceleration = code_value_linear_units(); SERIAL_ECHOPAIR("Setting Print and Travel Acceleration: ", planner.acceleration); SERIAL_EOL; } if (code_seen('P')) { planner.acceleration = code_value_linear_units(); SERIAL_ECHOPAIR("Setting Print Acceleration: ", planner.acceleration); SERIAL_EOL; } if (code_seen('R')) { planner.retract_acceleration = code_value_linear_units(); SERIAL_ECHOPAIR("Setting Retract Acceleration: ", planner.retract_acceleration); SERIAL_EOL; } if (code_seen('T')) { planner.travel_acceleration = code_value_linear_units(); SERIAL_ECHOPAIR("Setting Travel Acceleration: ", planner.travel_acceleration); SERIAL_EOL; } } /** * M205: Set Advanced Settings * * S = Min Feed Rate (units/s) * T = Min Travel Feed Rate (units/s) * B = Min Segment Time (碌s) * X = Max XY Jerk (units/sec^2) * Z = Max Z Jerk (units/sec^2) * E = Max E Jerk (units/sec^2) */ inline void gcode_M205() { if (code_seen('S')) planner.min_feedrate_mm_s = code_value_linear_units(); if (code_seen('T')) planner.min_travel_feedrate_mm_s = code_value_linear_units(); if (code_seen('B')) planner.min_segment_time = code_value_millis(); if (code_seen('X')) planner.max_xy_jerk = code_value_linear_units(); if (code_seen('Z')) planner.max_z_jerk = code_value_axis_units(Z_AXIS); if (code_seen('E')) planner.max_e_jerk = code_value_axis_units(E_AXIS); } /** * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y */ inline void gcode_M206() { LOOP_XYZ(i) if (code_seen(axis_codes[i])) set_home_offset((AxisEnum)i, code_value_axis_units(i)); #if ENABLED(SCARA) if (code_seen('T')) set_home_offset(X_AXIS, code_value_axis_units(X_AXIS)); // Theta if (code_seen('P')) set_home_offset(Y_AXIS, code_value_axis_units(Y_AXIS)); // Psi #endif SYNC_PLAN_POSITION_KINEMATIC(); report_current_position(); } #if ENABLED(DELTA) /** * M665: Set delta configurations * * L = diagonal rod * R = delta radius * S = segments per second * A = Alpha (Tower 1) diagonal rod trim * B = Beta (Tower 2) diagonal rod trim * C = Gamma (Tower 3) diagonal rod trim */ inline void gcode_M665() { if (code_seen('L')) delta_diagonal_rod = code_value_linear_units(); if (code_seen('R')) delta_radius = code_value_linear_units(); if (code_seen('S')) delta_segments_per_second = code_value_float(); if (code_seen('A')) delta_diagonal_rod_trim_tower_1 = code_value_linear_units(); if (code_seen('B')) delta_diagonal_rod_trim_tower_2 = code_value_linear_units(); if (code_seen('C')) delta_diagonal_rod_trim_tower_3 = code_value_linear_units(); recalc_delta_settings(delta_radius, delta_diagonal_rod); } /** * M666: Set delta endstop adjustment */ inline void gcode_M666() { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM(">>> gcode_M666"); } #endif LOOP_XYZ(i) { if (code_seen(axis_codes[i])) { endstop_adj[i] = code_value_axis_units(i); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPGM("endstop_adj["); SERIAL_ECHO(axis_codes[i]); SERIAL_ECHOPAIR("] = ", endstop_adj[i]); SERIAL_EOL; } #endif } } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOLNPGM("<<< gcode_M666"); } #endif } #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS) /** * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis. */ inline void gcode_M666() { if (code_seen('Z')) z_endstop_adj = code_value_axis_units(Z_AXIS); SERIAL_ECHOPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj); SERIAL_EOL; } #endif // !DELTA && Z_DUAL_ENDSTOPS #if ENABLED(FWRETRACT) /** * M207: Set firmware retraction values * * S[+units] retract_length * W[+units] retract_length_swap (multi-extruder) * F[units/min] retract_feedrate_mm_s * Z[units] retract_zlift */ inline void gcode_M207() { if (code_seen('S')) retract_length = code_value_axis_units(E_AXIS); if (code_seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(code_value_axis_units(E_AXIS)); if (code_seen('Z')) retract_zlift = code_value_axis_units(Z_AXIS); #if EXTRUDERS > 1 if (code_seen('W')) retract_length_swap = code_value_axis_units(E_AXIS); #endif } /** * M208: Set firmware un-retraction values * * S[+units] retract_recover_length (in addition to M207 S*) * W[+units] retract_recover_length_swap (multi-extruder) * F[units/min] retract_recover_feedrate_mm_s */ inline void gcode_M208() { if (code_seen('S')) retract_recover_length = code_value_axis_units(E_AXIS); if (code_seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(code_value_axis_units(E_AXIS)); #if EXTRUDERS > 1 if (code_seen('W')) retract_recover_length_swap = code_value_axis_units(E_AXIS); #endif } /** * M209: Enable automatic retract (M209 S1) * detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction. */ inline void gcode_M209() { if (code_seen('S')) { int t = code_value_int(); switch (t) { case 0: autoretract_enabled = false; break; case 1: autoretract_enabled = true; break; default: unknown_command_error(); return; } for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false; } } #endif // FWRETRACT #if HOTENDS > 1 /** * M218 - set hotend offset (in linear units) * * T<tool> * X<xoffset> * Y<yoffset> * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_EXTRUDER */ inline void gcode_M218() { if (get_target_extruder_from_command(218)) return; if (code_seen('X')) hotend_offset[X_AXIS][target_extruder] = code_value_axis_units(X_AXIS); if (code_seen('Y')) hotend_offset[Y_AXIS][target_extruder] = code_value_axis_units(Y_AXIS); #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_EXTRUDER) if (code_seen('Z')) hotend_offset[Z_AXIS][target_extruder] = code_value_axis_units(Z_AXIS); #endif SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_HOTEND_OFFSET); HOTEND_LOOP() { SERIAL_CHAR(' '); SERIAL_ECHO(hotend_offset[X_AXIS][e]); SERIAL_CHAR(','); SERIAL_ECHO(hotend_offset[Y_AXIS][e]); #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_EXTRUDER) SERIAL_CHAR(','); SERIAL_ECHO(hotend_offset[Z_AXIS][e]); #endif } SERIAL_EOL; } #endif // HOTENDS > 1 /** * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95) */ inline void gcode_M220() { if (code_seen('S')) feedrate_percentage = code_value_int(); } /** * M221: Set extrusion percentage (M221 T0 S95) */ inline void gcode_M221() { if (get_target_extruder_from_command(221)) return; if (code_seen('S')) extruder_multiplier[target_extruder] = code_value_int(); } /** * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>) */ inline void gcode_M226() { if (code_seen('P')) { int pin_number = code_value_int(); int pin_state = code_seen('S') ? code_value_int() : -1; // required pin state - default is inverted if (pin_state >= -1 && pin_state <= 1) { for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) { if (sensitive_pins[i] == pin_number) { pin_number = -1; break; } } if (pin_number > -1) { int target = LOW; stepper.synchronize(); pinMode(pin_number, INPUT); switch (pin_state) { case 1: target = HIGH; break; case 0: target = LOW; break; case -1: target = !digitalRead(pin_number); break; } while (digitalRead(pin_number) != target) idle(); } // pin_number > -1 } // pin_state -1 0 1 } // code_seen('P') } #if HAS_SERVOS /** * M280: Get or set servo position. P<index> [S<angle>] */ inline void gcode_M280() { if (!code_seen('P')) return; int servo_index = code_value_int(); if (servo_index >= 0 && servo_index < NUM_SERVOS) { if (code_seen('S')) MOVE_SERVO(servo_index, code_value_int()); else { SERIAL_ECHO_START; SERIAL_ECHOPGM(" Servo "); SERIAL_ECHO(servo_index); SERIAL_ECHOPGM(": "); SERIAL_ECHOLN(servo[servo_index].read()); } } else { SERIAL_ERROR_START; SERIAL_ERROR("Servo "); SERIAL_ERROR(servo_index); SERIAL_ERRORLN(" out of range"); } } #endif // HAS_SERVOS #if HAS_BUZZER /** * M300: Play beep sound S<frequency Hz> P<duration ms> */ inline void gcode_M300() { uint16_t const frequency = code_seen('S') ? code_value_ushort() : 260; uint16_t duration = code_seen('P') ? code_value_ushort() : 1000; // Limits the tone duration to 0-5 seconds. NOMORE(duration, 5000); BUZZ(duration, frequency); } #endif // HAS_BUZZER #if ENABLED(PIDTEMP) /** * M301: Set PID parameters P I D (and optionally C, L) * * P[float] Kp term * I[float] Ki term (unscaled) * D[float] Kd term (unscaled) * * With PID_EXTRUSION_SCALING: * * C[float] Kc term * L[float] LPQ length */ inline void gcode_M301() { // multi-extruder PID patch: M301 updates or prints a single extruder's PID values // default behaviour (omitting E parameter) is to update for extruder 0 only int e = code_seen('E') ? code_value_int() : 0; // extruder being updated if (e < HOTENDS) { // catch bad input value if (code_seen('P')) PID_PARAM(Kp, e) = code_value_float(); if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value_float()); if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value_float()); #if ENABLED(PID_EXTRUSION_SCALING) if (code_seen('C')) PID_PARAM(Kc, e) = code_value_float(); if (code_seen('L')) lpq_len = code_value_float(); NOMORE(lpq_len, LPQ_MAX_LEN); #endif thermalManager.updatePID(); SERIAL_ECHO_START; #if ENABLED(PID_PARAMS_PER_HOTEND) SERIAL_ECHOPGM(" e:"); // specify extruder in serial output SERIAL_ECHO(e); #endif // PID_PARAMS_PER_HOTEND SERIAL_ECHOPGM(" p:"); SERIAL_ECHO(PID_PARAM(Kp, e)); SERIAL_ECHOPGM(" i:"); SERIAL_ECHO(unscalePID_i(PID_PARAM(Ki, e))); SERIAL_ECHOPGM(" d:"); SERIAL_ECHO(unscalePID_d(PID_PARAM(Kd, e))); #if ENABLED(PID_EXTRUSION_SCALING) SERIAL_ECHOPGM(" c:"); //Kc does not have scaling applied above, or in resetting defaults SERIAL_ECHO(PID_PARAM(Kc, e)); #endif SERIAL_EOL; } else { SERIAL_ERROR_START; SERIAL_ERRORLN(MSG_INVALID_EXTRUDER); } } #endif // PIDTEMP #if ENABLED(PIDTEMPBED) inline void gcode_M304() { if (code_seen('P')) thermalManager.bedKp = code_value_float(); if (code_seen('I')) thermalManager.bedKi = scalePID_i(code_value_float()); if (code_seen('D')) thermalManager.bedKd = scalePID_d(code_value_float()); thermalManager.updatePID(); SERIAL_ECHO_START; SERIAL_ECHOPGM(" p:"); SERIAL_ECHO(thermalManager.bedKp); SERIAL_ECHOPGM(" i:"); SERIAL_ECHO(unscalePID_i(thermalManager.bedKi)); SERIAL_ECHOPGM(" d:"); SERIAL_ECHOLN(unscalePID_d(thermalManager.bedKd)); } #endif // PIDTEMPBED #if defined(CHDK) || HAS_PHOTOGRAPH /** * M240: Trigger a camera by emulating a Canon RC-1 * See http://www.doc-diy.net/photo/rc-1_hacked/ */ inline void gcode_M240() { #ifdef CHDK OUT_WRITE(CHDK, HIGH); chdkHigh = millis(); chdkActive = true; #elif HAS_PHOTOGRAPH const uint8_t NUM_PULSES = 16; const float PULSE_LENGTH = 0.01524; for (int i = 0; i < NUM_PULSES; i++) { WRITE(PHOTOGRAPH_PIN, HIGH); _delay_ms(PULSE_LENGTH); WRITE(PHOTOGRAPH_PIN, LOW); _delay_ms(PULSE_LENGTH); } delay(7.33); for (int i = 0; i < NUM_PULSES; i++) { WRITE(PHOTOGRAPH_PIN, HIGH); _delay_ms(PULSE_LENGTH); WRITE(PHOTOGRAPH_PIN, LOW); _delay_ms(PULSE_LENGTH); } #endif // !CHDK && HAS_PHOTOGRAPH } #endif // CHDK || PHOTOGRAPH_PIN #if HAS_LCD_CONTRAST /** * M250: Read and optionally set the LCD contrast */ inline void gcode_M250() { if (code_seen('C')) set_lcd_contrast(code_value_int()); SERIAL_PROTOCOLPGM("lcd contrast value: "); SERIAL_PROTOCOL(lcd_contrast); SERIAL_EOL; } #endif // HAS_LCD_CONTRAST #if ENABLED(PREVENT_DANGEROUS_EXTRUDE) /** * M302: Allow cold extrudes, or set the minimum extrude temperature * * S<temperature> sets the minimum extrude temperature * P<bool> enables (1) or disables (0) cold extrusion * * Examples: * * M302 ; report current cold extrusion state * M302 P0 ; enable cold extrusion checking * M302 P1 ; disables cold extrusion checking * M302 S0 ; always allow extrusion (disables checking) * M302 S170 ; only allow extrusion above 170 * M302 S170 P1 ; set min extrude temp to 170 but leave disabled */ inline void gcode_M302() { bool seen_S = code_seen('S'); if (seen_S) { thermalManager.extrude_min_temp = code_value_temp_abs(); thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0); } if (code_seen('P')) thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || code_value_bool(); else if (!seen_S) { // Report current state SERIAL_ECHO_START; SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis")); SERIAL_ECHOPAIR("abled (min temp ", int(thermalManager.extrude_min_temp + 0.5)); SERIAL_ECHOLNPGM("C)"); } } #endif // PREVENT_DANGEROUS_EXTRUDE /** * M303: PID relay autotune * * S<temperature> sets the target temperature. (default 150C) * E<extruder> (-1 for the bed) (default 0) * C<cycles> * U<bool> with a non-zero value will apply the result to current settings */ inline void gcode_M303() { #if HAS_PID_HEATING int e = code_seen('E') ? code_value_int() : 0; int c = code_seen('C') ? code_value_int() : 5; bool u = code_seen('U') && code_value_bool(); float temp = code_seen('S') ? code_value_temp_abs() : (e < 0 ? 70.0 : 150.0); if (e >= 0 && e < HOTENDS) target_extruder = e; KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output thermalManager.PID_autotune(temp, e, c, u); KEEPALIVE_STATE(IN_HANDLER); #else SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED); #endif } #if ENABLED(SCARA) bool SCARA_move_to_cal(uint8_t delta_x, uint8_t delta_y) { //SoftEndsEnabled = false; // Ignore soft endstops during calibration //SERIAL_ECHOLNPGM(" Soft endstops disabled"); if (IsRunning()) { //gcode_get_destination(); // For X Y Z E F delta[X_AXIS] = delta_x; delta[Y_AXIS] = delta_y; forward_kinematics_SCARA(delta); destination[X_AXIS] = delta[X_AXIS] / axis_scaling[X_AXIS]; destination[Y_AXIS] = delta[Y_AXIS] / axis_scaling[Y_AXIS]; prepare_move_to_destination(); //ok_to_send(); return true; } return false; } /** * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration) */ inline bool gcode_M360() { SERIAL_ECHOLNPGM(" Cal: Theta 0"); return SCARA_move_to_cal(0, 120); } /** * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree) */ inline bool gcode_M361() { SERIAL_ECHOLNPGM(" Cal: Theta 90"); return SCARA_move_to_cal(90, 130); } /** * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration) */ inline bool gcode_M362() { SERIAL_ECHOLNPGM(" Cal: Psi 0"); return SCARA_move_to_cal(60, 180); } /** * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree) */ inline bool gcode_M363() { SERIAL_ECHOLNPGM(" Cal: Psi 90"); return SCARA_move_to_cal(50, 90); } /** * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position) */ inline bool gcode_M364() { SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90"); return SCARA_move_to_cal(45, 135); } /** * M365: SCARA calibration: Scaling factor, X, Y, Z axis */ inline void gcode_M365() { LOOP_XYZ(i) if (code_seen(axis_codes[i])) axis_scaling[i] = code_value_float(); } #endif // SCARA #if ENABLED(EXT_SOLENOID) void enable_solenoid(uint8_t num) { switch (num) { case 0: OUT_WRITE(SOL0_PIN, HIGH); break; #if HAS_SOLENOID_1 case 1: OUT_WRITE(SOL1_PIN, HIGH); break; #endif #if HAS_SOLENOID_2 case 2: OUT_WRITE(SOL2_PIN, HIGH); break; #endif #if HAS_SOLENOID_3 case 3: OUT_WRITE(SOL3_PIN, HIGH); break; #endif default: SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID); break; } } void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); } void disable_all_solenoids() { OUT_WRITE(SOL0_PIN, LOW); OUT_WRITE(SOL1_PIN, LOW); OUT_WRITE(SOL2_PIN, LOW); OUT_WRITE(SOL3_PIN, LOW); } /** * M380: Enable solenoid on the active extruder */ inline void gcode_M380() { enable_solenoid_on_active_extruder(); } /** * M381: Disable all solenoids */ inline void gcode_M381() { disable_all_solenoids(); } #endif // EXT_SOLENOID /** * M400: Finish all moves */ inline void gcode_M400() { stepper.synchronize(); } #if HAS_BED_PROBE /** * M401: Engage Z Servo endstop if available */ inline void gcode_M401() { DEPLOY_PROBE(); } /** * M402: Retract Z Servo endstop if enabled */ inline void gcode_M402() { STOW_PROBE(); } #endif // HAS_BED_PROBE #if ENABLED(FILAMENT_WIDTH_SENSOR) /** * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0> */ inline void gcode_M404() { if (code_seen('W')) { filament_width_nominal = code_value_linear_units(); } else { SERIAL_PROTOCOLPGM("Filament dia (nominal mm):"); SERIAL_PROTOCOLLN(filament_width_nominal); } } /** * M405: Turn on filament sensor for control */ inline void gcode_M405() { // This is technically a linear measurement, but since it's quantized to centimeters and is a different unit than // everything else, it uses code_value_int() instead of code_value_linear_units(). if (code_seen('D')) meas_delay_cm = code_value_int(); NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY); if (filwidth_delay_index2 == -1) { // Initialize the ring buffer if not done since startup int temp_ratio = thermalManager.widthFil_to_size_ratio(); for (uint8_t i = 0; i < COUNT(measurement_delay); ++i) measurement_delay[i] = temp_ratio - 100; // Subtract 100 to scale within a signed byte filwidth_delay_index1 = filwidth_delay_index2 = 0; } filament_sensor = true; //SERIAL_PROTOCOLPGM("Filament dia (measured mm):"); //SERIAL_PROTOCOL(filament_width_meas); //SERIAL_PROTOCOLPGM("Extrusion ratio(%):"); //SERIAL_PROTOCOL(extruder_multiplier[active_extruder]); } /** * M406: Turn off filament sensor for control */ inline void gcode_M406() { filament_sensor = false; } /** * M407: Get measured filament diameter on serial output */ inline void gcode_M407() { SERIAL_PROTOCOLPGM("Filament dia (measured mm):"); SERIAL_PROTOCOLLN(filament_width_meas); } #endif // FILAMENT_WIDTH_SENSOR void quickstop_stepper() { stepper.quick_stop(); #if DISABLED(SCARA) stepper.synchronize(); LOOP_XYZ(i) set_current_from_steppers_for_axis((AxisEnum)i); SYNC_PLAN_POSITION_KINEMATIC(); #endif } #if ENABLED(MESH_BED_LEVELING) /** * M420: Enable/Disable Mesh Bed Leveling */ inline void gcode_M420() { if (code_seen('S') && code_has_value()) mbl.set_has_mesh(code_value_bool()); } /** * M421: Set a single Mesh Bed Leveling Z coordinate * Use either 'M421 X<linear> Y<linear> Z<linear>' or 'M421 I<xindex> J<yindex> Z<linear>' */ inline void gcode_M421() { int8_t px = 0, py = 0; float z = 0; bool hasX, hasY, hasZ, hasI, hasJ; if ((hasX = code_seen('X'))) px = mbl.probe_index_x(code_value_axis_units(X_AXIS)); if ((hasY = code_seen('Y'))) py = mbl.probe_index_y(code_value_axis_units(Y_AXIS)); if ((hasI = code_seen('I'))) px = code_value_axis_units(X_AXIS); if ((hasJ = code_seen('J'))) py = code_value_axis_units(Y_AXIS); if ((hasZ = code_seen('Z'))) z = code_value_axis_units(Z_AXIS); if (hasX && hasY && hasZ) { if (px >= 0 && py >= 0) mbl.set_z(px, py, z); else { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY); } } else if (hasI && hasJ && hasZ) { if (px >= 0 && px < MESH_NUM_X_POINTS && py >= 0 && py < MESH_NUM_Y_POINTS) mbl.set_z(px, py, z); else { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY); } } else { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS); } } #endif /** * M428: Set home_offset based on the distance between the * current_position and the nearest "reference point." * If an axis is past center its endstop position * is the reference-point. Otherwise it uses 0. This allows * the Z offset to be set near the bed when using a max endstop. * * M428 can't be used more than 2cm away from 0 or an endstop. * * Use M206 to set these values directly. */ inline void gcode_M428() { bool err = false; LOOP_XYZ(i) { if (axis_homed[i]) { float base = (current_position[i] > (sw_endstop_min[i] + sw_endstop_max[i]) * 0.5) ? base_home_pos(i) : 0, diff = current_position[i] - LOGICAL_POSITION(base, i); if (diff > -20 && diff < 20) { set_home_offset((AxisEnum)i, home_offset[i] - diff); } else { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR); LCD_ALERTMESSAGEPGM("Err: Too far!"); err = true; break; } } } } /** * M500: Store settings in EEPROM */ inline void gcode_M500() { Config_StoreSettings(); } /** * M501: Read settings from EEPROM */ inline void gcode_M501() { Config_RetrieveSettings(); } /** * M502: Revert to default settings */ inline void gcode_M502() { Config_ResetDefault(); } /** * M503: print settings currently in memory */ inline void gcode_M503() { Config_PrintSettings(code_seen('S') && !code_value_bool()); } #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) /** * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>) */ inline void gcode_M540() { if (code_seen('S')) stepper.abort_on_endstop_hit = code_value_bool(); } #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED #if HAS_BED_PROBE inline void gcode_M851() { SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET); SERIAL_CHAR(' '); if (code_seen('Z')) { float value = code_value_axis_units(Z_AXIS); if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) { zprobe_zoffset = value; SERIAL_ECHO(zprobe_zoffset); } else { SERIAL_ECHOPGM(MSG_Z_MIN); SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN); SERIAL_CHAR(' '); SERIAL_ECHOPGM(MSG_Z_MAX); SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX); } } else { SERIAL_ECHOPAIR(": ", zprobe_zoffset); } SERIAL_EOL; } #endif // HAS_BED_PROBE #if ENABLED(FILAMENT_CHANGE_FEATURE) /** * M600: Pause for filament change * * E[distance] - Retract the filament this far (negative value) * Z[distance] - Move the Z axis by this distance * X[position] - Move to this X position, with Y * Y[position] - Move to this Y position, with X * L[distance] - Retract distance for removal (manual reload) * * Default values are used for omitted arguments. * */ inline void gcode_M600() { if (thermalManager.tooColdToExtrude(active_extruder)) { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600); return; } // Show initial message and wait for synchronize steppers lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INIT); stepper.synchronize(); float lastpos[NUM_AXIS]; // Save current position of all axes LOOP_XYZE(i) lastpos[i] = destination[i] = current_position[i]; // Define runplan for move axes #if ENABLED(DELTA) #define RUNPLAN(RATE_MM_S) inverse_kinematics(destination); \ planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], RATE_MM_S, active_extruder); #else #define RUNPLAN(RATE_MM_S) line_to_destination(MMS_TO_MMM(RATE_MM_S)); #endif KEEPALIVE_STATE(IN_HANDLER); // Initial retract before move to filament change position if (code_seen('E')) destination[E_AXIS] += code_value_axis_units(E_AXIS); #if defined(FILAMENT_CHANGE_RETRACT_LENGTH) && FILAMENT_CHANGE_RETRACT_LENGTH > 0 else destination[E_AXIS] -= FILAMENT_CHANGE_RETRACT_LENGTH; #endif RUNPLAN(FILAMENT_CHANGE_RETRACT_FEEDRATE); // Lift Z axis float z_lift = code_seen('Z') ? code_value_axis_units(Z_AXIS) : #if defined(FILAMENT_CHANGE_Z_ADD) && FILAMENT_CHANGE_Z_ADD > 0 FILAMENT_CHANGE_Z_ADD #else 0 #endif ; if (z_lift > 0) { destination[Z_AXIS] += z_lift; NOMORE(destination[Z_AXIS], Z_MAX_POS); RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE); } // Move XY axes to filament exchange position if (code_seen('X')) destination[X_AXIS] = code_value_axis_units(X_AXIS); #ifdef FILAMENT_CHANGE_X_POS else destination[X_AXIS] = FILAMENT_CHANGE_X_POS; #endif if (code_seen('Y')) destination[Y_AXIS] = code_value_axis_units(Y_AXIS); #ifdef FILAMENT_CHANGE_Y_POS else destination[Y_AXIS] = FILAMENT_CHANGE_Y_POS; #endif RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE); stepper.synchronize(); lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_UNLOAD); // Unload filament if (code_seen('L')) destination[E_AXIS] += code_value_axis_units(E_AXIS); #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0 else destination[E_AXIS] -= FILAMENT_CHANGE_UNLOAD_LENGTH; #endif RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE); // Synchronize steppers and then disable extruders steppers for manual filament changing stepper.synchronize(); disable_e0(); disable_e1(); disable_e2(); disable_e3(); delay(100); #if HAS_BUZZER millis_t next_tick = 0; #endif // Wait for filament insert by user and press button lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INSERT); while (!lcd_clicked()) { #if HAS_BUZZER millis_t ms = millis(); if (ms >= next_tick) { BUZZ(300, 2000); next_tick = ms + 2500; // Beep every 2.5s while waiting } #endif idle(true); } delay(100); while (lcd_clicked()) idle(true); delay(100); // Show load message lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_LOAD); // Load filament if (code_seen('L')) destination[E_AXIS] -= code_value_axis_units(E_AXIS); #if defined(FILAMENT_CHANGE_LOAD_LENGTH) && FILAMENT_CHANGE_LOAD_LENGTH > 0 else destination[E_AXIS] += FILAMENT_CHANGE_LOAD_LENGTH; #endif RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE); stepper.synchronize(); #if defined(FILAMENT_CHANGE_EXTRUDE_LENGTH) && FILAMENT_CHANGE_EXTRUDE_LENGTH > 0 do { // Extrude filament to get into hotend lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_EXTRUDE); destination[E_AXIS] += FILAMENT_CHANGE_EXTRUDE_LENGTH; RUNPLAN(FILAMENT_CHANGE_EXTRUDE_FEEDRATE); stepper.synchronize(); // Ask user if more filament should be extruded KEEPALIVE_STATE(PAUSED_FOR_USER); lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_OPTION); while (filament_change_menu_response == FILAMENT_CHANGE_RESPONSE_WAIT_FOR) idle(true); KEEPALIVE_STATE(IN_HANDLER); } while (filament_change_menu_response != FILAMENT_CHANGE_RESPONSE_RESUME_PRINT); #endif lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_RESUME); KEEPALIVE_STATE(IN_HANDLER); // Set extruder to saved position current_position[E_AXIS] = lastpos[E_AXIS]; destination[E_AXIS] = lastpos[E_AXIS]; planner.set_e_position_mm(current_position[E_AXIS]); #if ENABLED(DELTA) // Move XYZ to starting position, then E inverse_kinematics(lastpos); planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], FILAMENT_CHANGE_XY_FEEDRATE, active_extruder); planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], lastpos[E_AXIS], FILAMENT_CHANGE_XY_FEEDRATE, active_extruder); #else // Move XY to starting position, then Z, then E destination[X_AXIS] = lastpos[X_AXIS]; destination[Y_AXIS] = lastpos[Y_AXIS]; RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE); destination[Z_AXIS] = lastpos[Z_AXIS]; RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE); #endif stepper.synchronize(); #if ENABLED(FILAMENT_RUNOUT_SENSOR) filament_ran_out = false; #endif // Show status screen lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_STATUS); } #endif // FILAMENT_CHANGE_FEATURE #if ENABLED(DUAL_X_CARRIAGE) /** * M605: Set dual x-carriage movement mode * * M605 S0: Full control mode. The slicer has full control over x-carriage movement * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn * units x-offset and an optional differential hotend temperature of * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate * the first with a spacing of 100mm in the x direction and 2 degrees hotter. * * Note: the X axis should be homed after changing dual x-carriage mode. */ inline void gcode_M605() { stepper.synchronize(); if (code_seen('S')) dual_x_carriage_mode = code_value_byte(); switch (dual_x_carriage_mode) { case DXC_DUPLICATION_MODE: if (code_seen('X')) duplicate_extruder_x_offset = max(code_value_axis_units(X_AXIS), X2_MIN_POS - x_home_pos(0)); if (code_seen('R')) duplicate_extruder_temp_offset = code_value_temp_diff(); SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_HOTEND_OFFSET); SERIAL_CHAR(' '); SERIAL_ECHO(hotend_offset[X_AXIS][0]); SERIAL_CHAR(','); SERIAL_ECHO(hotend_offset[Y_AXIS][0]); SERIAL_CHAR(' '); SERIAL_ECHO(duplicate_extruder_x_offset); SERIAL_CHAR(','); SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]); break; case DXC_FULL_CONTROL_MODE: case DXC_AUTO_PARK_MODE: break; default: dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; break; } active_extruder_parked = false; extruder_duplication_enabled = false; delayed_move_time = 0; } #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE) inline void gcode_M605() { stepper.synchronize(); extruder_duplication_enabled = code_seen('S') && code_value_int() == 2; SERIAL_ECHO_START; SERIAL_ECHOPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF); SERIAL_EOL; } #endif // M605 #if ENABLED(LIN_ADVANCE) /** * M905: Set advance factor */ inline void gcode_M905() { stepper.synchronize(); stepper.advance_M905(code_seen('K') ? code_value_float() : -1.0); } #endif /** * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S */ inline void gcode_M907() { #if HAS_DIGIPOTSS LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.digipot_current(i, code_value_int()); if (code_seen('B')) stepper.digipot_current(4, code_value_int()); if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.digipot_current(i, code_value_int()); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY) if (code_seen('X')) stepper.digipot_current(0, code_value_int()); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z) if (code_seen('Z')) stepper.digipot_current(1, code_value_int()); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_E) if (code_seen('E')) stepper.digipot_current(2, code_value_int()); #endif #if ENABLED(DIGIPOT_I2C) // this one uses actual amps in floating point LOOP_XYZE(i) if (code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value_float()); // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...) for (int i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (code_seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, code_value_float()); #endif #if ENABLED(DAC_STEPPER_CURRENT) if (code_seen('S')) { float dac_percent = code_value_float(); for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent); } LOOP_XYZE(i) if (code_seen(axis_codes[i])) dac_current_percent(i, code_value_float()); #endif } #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT) /** * M908: Control digital trimpot directly (M908 P<pin> S<current>) */ inline void gcode_M908() { #if HAS_DIGIPOTSS stepper.digitalPotWrite( code_seen('P') ? code_value_int() : 0, code_seen('S') ? code_value_int() : 0 ); #endif #ifdef DAC_STEPPER_CURRENT dac_current_raw( code_seen('P') ? code_value_byte() : -1, code_seen('S') ? code_value_ushort() : 0 ); #endif } #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF inline void gcode_M909() { dac_print_values(); } inline void gcode_M910() { dac_commit_eeprom(); } #endif #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT #if HAS_MICROSTEPS // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers. inline void gcode_M350() { if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, code_value_byte()); LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_mode(i, code_value_byte()); if (code_seen('B')) stepper.microstep_mode(4, code_value_byte()); stepper.microstep_readings(); } /** * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B * S# determines MS1 or MS2, X# sets the pin high/low. */ inline void gcode_M351() { if (code_seen('S')) switch (code_value_byte()) { case 1: LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, code_value_byte(), -1); if (code_seen('B')) stepper.microstep_ms(4, code_value_byte(), -1); break; case 2: LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, -1, code_value_byte()); if (code_seen('B')) stepper.microstep_ms(4, -1, code_value_byte()); break; } stepper.microstep_readings(); } #endif // HAS_MICROSTEPS #if ENABLED(MIXING_EXTRUDER) /** * M163: Set a single mix factor for a mixing extruder * This is called "weight" by some systems. * * S[index] The channel index to set * P[float] The mix value * */ inline void gcode_M163() { int mix_index = code_seen('S') ? code_value_int() : 0; float mix_value = code_seen('P') ? code_value_float() : 0.0; if (mix_index < MIXING_STEPPERS) mixing_factor[mix_index] = mix_value; } #if MIXING_VIRTUAL_TOOLS > 1 /** * M164: Store the current mix factors as a virtual tool. * * S[index] The virtual tool to store * */ inline void gcode_M164() { int tool_index = code_seen('S') ? code_value_int() : 0; if (tool_index < MIXING_VIRTUAL_TOOLS) { normalize_mix(); for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i]; } } #endif #if ENABLED(DIRECT_MIXING_IN_G1) /** * M165: Set multiple mix factors for a mixing extruder. * Factors that are left out will be set to 0. * All factors together must add up to 1.0. * * A[factor] Mix factor for extruder stepper 1 * B[factor] Mix factor for extruder stepper 2 * C[factor] Mix factor for extruder stepper 3 * D[factor] Mix factor for extruder stepper 4 * H[factor] Mix factor for extruder stepper 5 * I[factor] Mix factor for extruder stepper 6 * */ inline void gcode_M165() { gcode_get_mix(); } #endif #endif // MIXING_EXTRUDER /** * M999: Restart after being stopped * * Default behaviour is to flush the serial buffer and request * a resend to the host starting on the last N line received. * * Sending "M999 S1" will resume printing without flushing the * existing command buffer. * */ inline void gcode_M999() { Running = true; lcd_reset_alert_level(); if (code_seen('S') && code_value_bool()) return; // gcode_LastN = Stopped_gcode_LastN; FlushSerialRequestResend(); } #if ENABLED(SWITCHING_EXTRUDER) inline void move_extruder_servo(uint8_t e) { const int angles[2] = SWITCHING_EXTRUDER_SERVO_ANGLES; MOVE_SERVO(SWITCHING_EXTRUDER_SERVO_NR, angles[e]); } #endif inline void invalid_extruder_error(const uint8_t &e) { SERIAL_ECHO_START; SERIAL_CHAR('T'); SERIAL_PROTOCOL_F(e, DEC); SERIAL_ECHOLN(MSG_INVALID_EXTRUDER); } void tool_change(const uint8_t tmp_extruder, const float fr_mm_m/*=0.0*/, bool no_move/*=false*/) { #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1 if (tmp_extruder >= MIXING_VIRTUAL_TOOLS) { invalid_extruder_error(tmp_extruder); return; } // T0-Tnnn: Switch virtual tool by changing the mix for (uint8_t j = 0; j < MIXING_STEPPERS; j++) mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j]; #else //!MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1 #if HOTENDS > 1 if (tmp_extruder >= EXTRUDERS) { invalid_extruder_error(tmp_extruder); return; } float old_feedrate_mm_m = feedrate_mm_m; feedrate_mm_m = fr_mm_m > 0.0 ? (old_feedrate_mm_m = fr_mm_m) : XY_PROBE_FEEDRATE_MM_M; if (tmp_extruder != active_extruder) { if (!no_move && axis_unhomed_error(true, true, true)) { SERIAL_ECHOLNPGM("No move on toolchange"); no_move = true; } // Save current position to destination, for use later set_destination_to_current(); #if ENABLED(DUAL_X_CARRIAGE) #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPGM("Dual X Carriage Mode "); switch (dual_x_carriage_mode) { case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break; case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break; case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break; } } #endif if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && IsRunning() && (delayed_move_time || current_position[X_AXIS] != x_home_pos(active_extruder)) ) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("Raise to ", current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT); SERIAL_EOL; SERIAL_ECHOPAIR("MoveX to ", x_home_pos(active_extruder)); SERIAL_EOL; SERIAL_ECHOPAIR("Lower to ", current_position[Z_AXIS]); SERIAL_EOL; } #endif // Park old head: 1) raise 2) move to park position 3) lower for (uint8_t i = 0; i < 3; i++) planner.buffer_line( i == 0 ? current_position[X_AXIS] : x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + (i == 2 ? 0 : TOOLCHANGE_PARK_ZLIFT), current_position[E_AXIS], planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS], active_extruder ); stepper.synchronize(); } // apply Y & Z extruder offset (x offset is already used in determining home pos) current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder]; current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder]; active_extruder = tmp_extruder; // This function resets the max/min values - the current position may be overwritten below. set_axis_is_at_home(X_AXIS); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position); #endif switch (dual_x_carriage_mode) { case DXC_FULL_CONTROL_MODE: current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos); inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]); break; case DXC_DUPLICATION_MODE: active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position if (active_extruder_parked) current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos); else current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset; inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]); extruder_duplication_enabled = false; break; default: // record raised toolhead position for use by unpark memcpy(raised_parked_position, current_position, sizeof(raised_parked_position)); raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT; active_extruder_parked = true; delayed_move_time = 0; break; } #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no"); SERIAL_EOL; DEBUG_POS("New extruder (parked)", current_position); } #endif // No extra case for AUTO_BED_LEVELING_FEATURE in DUAL_X_CARRIAGE. Does that mean they don't work together? #else // !DUAL_X_CARRIAGE #if ENABLED(SWITCHING_EXTRUDER) // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower. float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder], z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0); // Always raise by some amount planner.buffer_line( current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + z_raise, current_position[E_AXIS], planner.max_feedrate_mm_s[Z_AXIS], active_extruder ); stepper.synchronize(); move_extruder_servo(active_extruder); delay(500); // Move back down, if needed if (z_raise != z_diff) { planner.buffer_line( current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + z_diff, current_position[E_AXIS], planner.max_feedrate_mm_s[Z_AXIS], active_extruder ); stepper.synchronize(); } #endif /** * Set current_position to the position of the new nozzle. * Offsets are based on linear distance, so we need to get * the resulting position in coordinate space. * * - With grid or 3-point leveling, offset XYZ by a tilted vector * - With mesh leveling, update Z for the new position * - Otherwise, just use the raw linear distance * * Software endstops are altered here too. Consider a case where: * E0 at X=0 ... E1 at X=10 * When we switch to E1 now X=10, but E1 can't move left. * To express this we apply the change in XY to the software endstops. * E1 can move farther right than E0, so the right limit is extended. * * Note that we don't adjust the Z software endstops. Why not? * Consider a case where Z=0 (here) and switching to E1 makes Z=1 * because the bed is 1mm lower at the new position. As long as * the first nozzle is out of the way, the carriage should be * allowed to move 1mm lower. This technically "breaks" the * Z software endstop. But this is technically correct (and * there is no viable alternative). */ #if ENABLED(AUTO_BED_LEVELING_FEATURE) // Offset extruder, make sure to apply the bed level rotation matrix vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder], hotend_offset[Y_AXIS][tmp_extruder], 0), act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder], hotend_offset[Y_AXIS][active_extruder], 0), offset_vec = tmp_offset_vec - act_offset_vec; #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { tmp_offset_vec.debug("tmp_offset_vec"); act_offset_vec.debug("act_offset_vec"); offset_vec.debug("offset_vec (BEFORE)"); } #endif offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix)); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) offset_vec.debug("offset_vec (AFTER)"); #endif // Adjustments to the current position float xydiff[2] = { offset_vec.x, offset_vec.y }; current_position[Z_AXIS] += offset_vec.z; #else // !AUTO_BED_LEVELING_FEATURE float xydiff[2] = { hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder], hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder] }; #if ENABLED(MESH_BED_LEVELING) if (mbl.active()) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]); #endif float xpos = RAW_CURRENT_POSITION(X_AXIS), ypos = RAW_CURRENT_POSITION(Y_AXIS); current_position[Z_AXIS] += mbl.get_z(xpos + xydiff[X_AXIS], ypos + xydiff[Y_AXIS]) - mbl.get_z(xpos, ypos); #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(" after: ", current_position[Z_AXIS]); SERIAL_EOL; } #endif } #endif // MESH_BED_LEVELING #endif // !AUTO_BED_LEVELING_FEATURE #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]); SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]); SERIAL_ECHOLNPGM(" }"); } #endif // The newly-selected extruder XY is actually at... current_position[X_AXIS] += xydiff[X_AXIS]; current_position[Y_AXIS] += xydiff[Y_AXIS]; for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) { position_shift[i] += xydiff[i]; update_software_endstops((AxisEnum)i); } // Set the new active extruder active_extruder = tmp_extruder; #endif // !DUAL_X_CARRIAGE #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position); #endif // Tell the planner the new "current position" SYNC_PLAN_POSITION_KINEMATIC(); // Move to the "old position" (move the extruder into place) if (!no_move && IsRunning()) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination); #endif prepare_move_to_destination(); } } // (tmp_extruder != active_extruder) stepper.synchronize(); #if ENABLED(EXT_SOLENOID) disable_all_solenoids(); enable_solenoid_on_active_extruder(); #endif // EXT_SOLENOID feedrate_mm_m = old_feedrate_mm_m; #else // HOTENDS <= 1 // Set the new active extruder active_extruder = tmp_extruder; UNUSED(fr_mm_m); UNUSED(no_move); #endif // HOTENDS <= 1 SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_ACTIVE_EXTRUDER); SERIAL_PROTOCOLLN((int)active_extruder); #endif //!MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1 } /** * T0-T3: Switch tool, usually switching extruders * * F[units/min] Set the movement feedrate * S1 Don't move the tool in XY after change */ inline void gcode_T(uint8_t tmp_extruder) { #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder); SERIAL_ECHOLNPGM(")"); DEBUG_POS("BEFORE", current_position); } #endif #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1) tool_change(tmp_extruder); #elif HOTENDS > 1 tool_change( tmp_extruder, code_seen('F') ? code_value_axis_units(X_AXIS) : 0.0, (tmp_extruder == active_extruder) || (code_seen('S') && code_value_bool()) ); #endif #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING)) { DEBUG_POS("AFTER", current_position); SERIAL_ECHOLNPGM("<<< gcode_T"); } #endif } /** * Process a single command and dispatch it to its handler * This is called from the main loop() */ void process_next_command() { current_command = command_queue[cmd_queue_index_r]; if (DEBUGGING(ECHO)) { SERIAL_ECHO_START; SERIAL_ECHOLN(current_command); } // Sanitize the current command: // - Skip leading spaces // - Bypass N[-0-9][0-9]*[ ]* // - Overwrite * with nul to mark the end while (*current_command == ' ') ++current_command; if (*current_command == 'N' && NUMERIC_SIGNED(current_command[1])) { current_command += 2; // skip N[-0-9] while (NUMERIC(*current_command)) ++current_command; // skip [0-9]* while (*current_command == ' ') ++current_command; // skip [ ]* } char* starpos = strchr(current_command, '*'); // * should always be the last parameter if (starpos) while (*starpos == ' ' || *starpos == '*') *starpos-- = '\0'; // nullify '*' and ' ' char *cmd_ptr = current_command; // Get the command code, which must be G, M, or T char command_code = *cmd_ptr++; // Skip spaces to get the numeric part while (*cmd_ptr == ' ') cmd_ptr++; uint16_t codenum = 0; // define ahead of goto // Bail early if there's no code bool code_is_good = NUMERIC(*cmd_ptr); if (!code_is_good) goto ExitUnknownCommand; // Get and skip the code number do { codenum = (codenum * 10) + (*cmd_ptr - '0'); cmd_ptr++; } while (NUMERIC(*cmd_ptr)); // Skip all spaces to get to the first argument, or nul while (*cmd_ptr == ' ') cmd_ptr++; // The command's arguments (if any) start here, for sure! current_command_args = cmd_ptr; KEEPALIVE_STATE(IN_HANDLER); // Handle a known G, M, or T switch (command_code) { case 'G': switch (codenum) { // G0, G1 case 0: case 1: gcode_G0_G1(); break; // G2, G3 #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA) case 2: // G2 - CW ARC case 3: // G3 - CCW ARC gcode_G2_G3(codenum == 2); break; #endif // G4 Dwell case 4: gcode_G4(); break; #if ENABLED(BEZIER_CURVE_SUPPORT) // G5 case 5: // G5 - Cubic B_spline gcode_G5(); break; #endif // BEZIER_CURVE_SUPPORT #if ENABLED(FWRETRACT) case 10: // G10: retract case 11: // G11: retract_recover gcode_G10_G11(codenum == 10); break; #endif // FWRETRACT #if ENABLED(NOZZLE_CLEAN_FEATURE) case 12: gcode_G12(); // G12: Nozzle Clean break; #endif // NOZZLE_CLEAN_FEATURE #if ENABLED(INCH_MODE_SUPPORT) case 20: //G20: Inch Mode gcode_G20(); break; case 21: //G21: MM Mode gcode_G21(); break; #endif // INCH_MODE_SUPPORT #if ENABLED(NOZZLE_PARK_FEATURE) case 27: // G27: Nozzle Park gcode_G27(); break; #endif // NOZZLE_PARK_FEATURE case 28: // G28: Home all axes, one at a time gcode_G28(); break; #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING) case 29: // G29 Detailed Z probe, probes the bed at 3 or more points. gcode_G29(); break; #endif // AUTO_BED_LEVELING_FEATURE #if HAS_BED_PROBE case 30: // G30 Single Z probe gcode_G30(); break; #if ENABLED(Z_PROBE_SLED) case 31: // G31: dock the sled gcode_G31(); break; case 32: // G32: undock the sled gcode_G32(); break; #endif // Z_PROBE_SLED #endif // HAS_BED_PROBE case 90: // G90 relative_mode = false; break; case 91: // G91 relative_mode = true; break; case 92: // G92 gcode_G92(); break; } break; case 'M': switch (codenum) { #if ENABLED(ULTIPANEL) case 0: // M0 - Unconditional stop - Wait for user button press on LCD case 1: // M1 - Conditional stop - Wait for user button press on LCD gcode_M0_M1(); break; #endif // ULTIPANEL case 17: gcode_M17(); break; #if ENABLED(SDSUPPORT) case 20: // M20 - list SD card gcode_M20(); break; case 21: // M21 - init SD card gcode_M21(); break; case 22: //M22 - release SD card gcode_M22(); break; case 23: //M23 - Select file gcode_M23(); break; case 24: //M24 - Start SD print gcode_M24(); break; case 25: //M25 - Pause SD print gcode_M25(); break; case 26: //M26 - Set SD index gcode_M26(); break; case 27: //M27 - Get SD status gcode_M27(); break; case 28: //M28 - Start SD write gcode_M28(); break; case 29: //M29 - Stop SD write gcode_M29(); break; case 30: //M30 <filename> Delete File gcode_M30(); break; case 32: //M32 - Select file and start SD print gcode_M32(); break; #if ENABLED(LONG_FILENAME_HOST_SUPPORT) case 33: //M33 - Get the long full path to a file or folder gcode_M33(); break; #endif // LONG_FILENAME_HOST_SUPPORT case 928: //M928 - Start SD write gcode_M928(); break; #endif //SDSUPPORT case 31: //M31 take time since the start of the SD print or an M109 command gcode_M31(); break; case 42: //M42 -Change pin status via gcode gcode_M42(); break; #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST) case 48: // M48 Z probe repeatability gcode_M48(); break; #endif // Z_MIN_PROBE_REPEATABILITY_TEST case 75: // Start print timer gcode_M75(); break; case 76: // Pause print timer gcode_M76(); break; case 77: // Stop print timer gcode_M77(); break; #if ENABLED(PRINTCOUNTER) case 78: // Show print statistics gcode_M78(); break; #endif #if ENABLED(M100_FREE_MEMORY_WATCHER) case 100: gcode_M100(); break; #endif case 104: // M104 gcode_M104(); break; case 110: // M110: Set Current Line Number gcode_M110(); break; case 111: // M111: Set debug level gcode_M111(); break; #if DISABLED(EMERGENCY_PARSER) case 108: // M108: Cancel Waiting gcode_M108(); break; case 112: // M112: Emergency Stop gcode_M112(); break; case 410: // M410 quickstop - Abort all the planned moves. gcode_M410(); break; #endif #if ENABLED(HOST_KEEPALIVE_FEATURE) case 113: // M113: Set Host Keepalive interval gcode_M113(); break; #endif case 140: // M140: Set bed temp gcode_M140(); break; case 105: // M105: Read current temperature gcode_M105(); KEEPALIVE_STATE(NOT_BUSY); return; // "ok" already printed case 109: // M109: Wait for temperature gcode_M109(); break; #if HAS_TEMP_BED case 190: // M190: Wait for bed heater to reach target gcode_M190(); break; #endif // HAS_TEMP_BED #if FAN_COUNT > 0 case 106: // M106: Fan On gcode_M106(); break; case 107: // M107: Fan Off gcode_M107(); break; #endif // FAN_COUNT > 0 #if ENABLED(BARICUDA) // PWM for HEATER_1_PIN #if HAS_HEATER_1 case 126: // M126: valve open gcode_M126(); break; case 127: // M127: valve closed gcode_M127(); break; #endif // HAS_HEATER_1 // PWM for HEATER_2_PIN #if HAS_HEATER_2 case 128: // M128: valve open gcode_M128(); break; case 129: // M129: valve closed gcode_M129(); break; #endif // HAS_HEATER_2 #endif // BARICUDA #if HAS_POWER_SWITCH case 80: // M80: Turn on Power Supply gcode_M80(); break; #endif // HAS_POWER_SWITCH case 81: // M81: Turn off Power, including Power Supply, if possible gcode_M81(); break; case 82: gcode_M82(); break; case 83: gcode_M83(); break; case 18: // (for compatibility) case 84: // M84 gcode_M18_M84(); break; case 85: // M85 gcode_M85(); break; case 92: // M92: Set the steps-per-unit for one or more axes gcode_M92(); break; case 115: // M115: Report capabilities gcode_M115(); break; case 117: // M117: Set LCD message text, if possible gcode_M117(); break; case 114: // M114: Report current position gcode_M114(); break; case 120: // M120: Enable endstops gcode_M120(); break; case 121: // M121: Disable endstops gcode_M121(); break; case 119: // M119: Report endstop states gcode_M119(); break; #if ENABLED(ULTIPANEL) case 145: // M145: Set material heatup parameters gcode_M145(); break; #endif #if ENABLED(TEMPERATURE_UNITS_SUPPORT) case 149: gcode_M149(); break; #endif #if ENABLED(BLINKM) case 150: // M150 gcode_M150(); break; #endif //BLINKM #if ENABLED(EXPERIMENTAL_I2CBUS) case 155: gcode_M155(); break; case 156: gcode_M156(); break; #endif //EXPERIMENTAL_I2CBUS #if ENABLED(MIXING_EXTRUDER) case 163: // M163 S<int> P<float> set weight for a mixing extruder gcode_M163(); break; #if MIXING_VIRTUAL_TOOLS > 1 case 164: // M164 S<int> save current mix as a virtual extruder gcode_M164(); break; #endif #if ENABLED(DIRECT_MIXING_IN_G1) case 165: // M165 [ABCDHI]<float> set multiple mix weights gcode_M165(); break; #endif #endif case 200: // M200 D<diameter> Set filament diameter and set E axis units to cubic. (Use S0 to revert to linear units.) gcode_M200(); break; case 201: // M201 gcode_M201(); break; #if 0 // Not used for Sprinter/grbl gen6 case 202: // M202 gcode_M202(); break; #endif case 203: // M203 max feedrate units/sec gcode_M203(); break; case 204: // M204 acclereration S normal moves T filmanent only moves gcode_M204(); break; case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk gcode_M205(); break; case 206: // M206 additional homing offset gcode_M206(); break; #if ENABLED(DELTA) case 665: // M665 set delta configurations L<diagonal_rod> R<delta_radius> S<segments_per_sec> gcode_M665(); break; #endif #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS) case 666: // M666 set delta / dual endstop adjustment gcode_M666(); break; #endif #if ENABLED(FWRETRACT) case 207: // M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance> gcode_M207(); break; case 208: // M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min> gcode_M208(); break; case 209: // M209 - Turn Automatic Retract Detection on/off: S<bool> (For slicers that don't support G10/11). Every normal extrude-only move will be classified as retract depending on the direction. gcode_M209(); break; #endif // FWRETRACT #if HOTENDS > 1 case 218: // M218 - Set a tool offset: T<index> X<offset> Y<offset> gcode_M218(); break; #endif case 220: // M220 - Set Feedrate Percentage: S<percent> ("FR" on your LCD) gcode_M220(); break; case 221: // M221 - Set Flow Percentage: S<percent> gcode_M221(); break; case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required gcode_M226(); break; #if HAS_SERVOS case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds gcode_M280(); break; #endif // HAS_SERVOS #if HAS_BUZZER case 300: // M300 - Play beep tone gcode_M300(); break; #endif // HAS_BUZZER #if ENABLED(PIDTEMP) case 301: // M301 gcode_M301(); break; #endif // PIDTEMP #if ENABLED(PIDTEMPBED) case 304: // M304 gcode_M304(); break; #endif // PIDTEMPBED #if defined(CHDK) || HAS_PHOTOGRAPH case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/ gcode_M240(); break; #endif // CHDK || PHOTOGRAPH_PIN #if HAS_LCD_CONTRAST case 250: // M250 Set LCD contrast value: C<value> (value 0..63) gcode_M250(); break; #endif // HAS_LCD_CONTRAST #if ENABLED(PREVENT_DANGEROUS_EXTRUDE) case 302: // allow cold extrudes, or set the minimum extrude temperature gcode_M302(); break; #endif // PREVENT_DANGEROUS_EXTRUDE case 303: // M303 PID autotune gcode_M303(); break; #if ENABLED(SCARA) case 360: // M360 SCARA Theta pos1 if (gcode_M360()) return; break; case 361: // M361 SCARA Theta pos2 if (gcode_M361()) return; break; case 362: // M362 SCARA Psi pos1 if (gcode_M362()) return; break; case 363: // M363 SCARA Psi pos2 if (gcode_M363()) return; break; case 364: // M364 SCARA Psi pos3 (90 deg to Theta) if (gcode_M364()) return; break; case 365: // M365 Set SCARA scaling for X Y Z gcode_M365(); break; #endif // SCARA case 400: // M400 finish all moves gcode_M400(); break; #if HAS_BED_PROBE case 401: gcode_M401(); break; case 402: gcode_M402(); break; #endif // HAS_BED_PROBE #if ENABLED(FILAMENT_WIDTH_SENSOR) case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width gcode_M404(); break; case 405: //M405 Turn on filament sensor for control gcode_M405(); break; case 406: //M406 Turn off filament sensor for control gcode_M406(); break; case 407: //M407 Display measured filament diameter gcode_M407(); break; #endif // ENABLED(FILAMENT_WIDTH_SENSOR) #if ENABLED(MESH_BED_LEVELING) case 420: // M420 Enable/Disable Mesh Bed Leveling gcode_M420(); break; case 421: // M421 Set a Mesh Bed Leveling Z coordinate gcode_M421(); break; #endif case 428: // M428 Apply current_position to home_offset gcode_M428(); break; case 500: // M500 Store settings in EEPROM gcode_M500(); break; case 501: // M501 Read settings from EEPROM gcode_M501(); break; case 502: // M502 Revert to default settings gcode_M502(); break; case 503: // M503 print settings currently in memory gcode_M503(); break; #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) case 540: gcode_M540(); break; #endif #if HAS_BED_PROBE case 851: gcode_M851(); break; #endif // HAS_BED_PROBE #if ENABLED(FILAMENT_CHANGE_FEATURE) case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal] gcode_M600(); break; #endif // FILAMENT_CHANGE_FEATURE #if ENABLED(DUAL_X_CARRIAGE) case 605: gcode_M605(); break; #endif // DUAL_X_CARRIAGE #if ENABLED(LIN_ADVANCE) case 905: // M905 Set advance factor. gcode_M905(); break; #endif case 907: // M907 Set digital trimpot motor current using axis codes. gcode_M907(); break; #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT) case 908: // M908 Control digital trimpot directly. gcode_M908(); break; #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF case 909: // M909 Print digipot/DAC current value gcode_M909(); break; case 910: // M910 Commit digipot/DAC value to external EEPROM gcode_M910(); break; #endif #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT #if HAS_MICROSTEPS case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers. gcode_M350(); break; case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low. gcode_M351(); break; #endif // HAS_MICROSTEPS case 999: // M999: Restart after being Stopped gcode_M999(); break; } break; case 'T': gcode_T(codenum); break; default: code_is_good = false; } KEEPALIVE_STATE(NOT_BUSY); ExitUnknownCommand: // Still unknown command? Throw an error if (!code_is_good) unknown_command_error(); ok_to_send(); } void FlushSerialRequestResend() { //char command_queue[cmd_queue_index_r][100]="Resend:"; MYSERIAL.flush(); SERIAL_PROTOCOLPGM(MSG_RESEND); SERIAL_PROTOCOLLN(gcode_LastN + 1); ok_to_send(); } void ok_to_send() { refresh_cmd_timeout(); if (!send_ok[cmd_queue_index_r]) return; SERIAL_PROTOCOLPGM(MSG_OK); #if ENABLED(ADVANCED_OK) char* p = command_queue[cmd_queue_index_r]; if (*p == 'N') { SERIAL_PROTOCOL(' '); SERIAL_ECHO(*p++); while (NUMERIC_SIGNED(*p)) SERIAL_ECHO(*p++); } SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1)); SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue); #endif SERIAL_EOL; } void clamp_to_software_endstops(float target[3]) { if (min_software_endstops) { NOLESS(target[X_AXIS], sw_endstop_min[X_AXIS]); NOLESS(target[Y_AXIS], sw_endstop_min[Y_AXIS]); NOLESS(target[Z_AXIS], sw_endstop_min[Z_AXIS]); } if (max_software_endstops) { NOMORE(target[X_AXIS], sw_endstop_max[X_AXIS]); NOMORE(target[Y_AXIS], sw_endstop_max[Y_AXIS]); NOMORE(target[Z_AXIS], sw_endstop_max[Z_AXIS]); } } #if ENABLED(DELTA) void recalc_delta_settings(float radius, float diagonal_rod) { delta_tower1_x = -SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower delta_tower1_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1); delta_tower2_x = SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower delta_tower2_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2); delta_tower3_x = 0.0; // back middle tower delta_tower3_y = (radius + DELTA_RADIUS_TRIM_TOWER_3); delta_diagonal_rod_2_tower_1 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_1); delta_diagonal_rod_2_tower_2 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_2); delta_diagonal_rod_2_tower_3 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_3); } void inverse_kinematics(const float in_cartesian[3]) { const float cartesian[3] = { RAW_X_POSITION(in_cartesian[X_AXIS]), RAW_Y_POSITION(in_cartesian[Y_AXIS]), RAW_Z_POSITION(in_cartesian[Z_AXIS]) }; delta[TOWER_1] = sqrt(delta_diagonal_rod_2_tower_1 - sq(delta_tower1_x - cartesian[X_AXIS]) - sq(delta_tower1_y - cartesian[Y_AXIS]) ) + cartesian[Z_AXIS]; delta[TOWER_2] = sqrt(delta_diagonal_rod_2_tower_2 - sq(delta_tower2_x - cartesian[X_AXIS]) - sq(delta_tower2_y - cartesian[Y_AXIS]) ) + cartesian[Z_AXIS]; delta[TOWER_3] = sqrt(delta_diagonal_rod_2_tower_3 - sq(delta_tower3_x - cartesian[X_AXIS]) - sq(delta_tower3_y - cartesian[Y_AXIS]) ) + cartesian[Z_AXIS]; /** SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]); SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]); SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]); SERIAL_ECHOPGM("delta a="); SERIAL_ECHO(delta[TOWER_1]); SERIAL_ECHOPGM(" b="); SERIAL_ECHO(delta[TOWER_2]); SERIAL_ECHOPGM(" c="); SERIAL_ECHOLN(delta[TOWER_3]); */ } float delta_safe_distance_from_top() { float cartesian[3] = { LOGICAL_X_POSITION(0), LOGICAL_Y_POSITION(0), LOGICAL_Z_POSITION(0) }; inverse_kinematics(cartesian); float distance = delta[TOWER_3]; cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS); inverse_kinematics(cartesian); return abs(distance - delta[TOWER_3]); } void forward_kinematics_DELTA(float z1, float z2, float z3) { //As discussed in Wikipedia "Trilateration" //we are establishing a new coordinate //system in the plane of the three carriage points. //This system will have the origin at tower1 and //tower2 is on the x axis. tower3 is in the X-Y //plane with a Z component of zero. We will define unit //vectors in this coordinate system in our original //coordinate system. Then when we calculate the //Xnew, Ynew and Znew values, we can translate back into //the original system by moving along those unit vectors //by the corresponding values. // https://en.wikipedia.org/wiki/Trilateration // Variable names matched to Marlin, c-version // and avoiding a vector library // by Andreas Hardtung 2016-06-7 // based on a Java function from // "Delta Robot Kinematics by Steve Graves" V3 // Result is in cartesian_position[]. //Create a vector in old coordinates along x axis of new coordinate float p12[3] = { delta_tower2_x - delta_tower1_x, delta_tower2_y - delta_tower1_y, z2 - z1 }; //Get the Magnitude of vector. float d = sqrt( p12[0]*p12[0] + p12[1]*p12[1] + p12[2]*p12[2] ); //Create unit vector by dividing by magnitude. float ex[3] = { p12[0]/d, p12[1]/d, p12[2]/d }; //Now find vector from the origin of the new system to the third point. float p13[3] = { delta_tower3_x - delta_tower1_x, delta_tower3_y - delta_tower1_y, z3 - z1 }; //Now use dot product to find the component of this vector on the X axis. float i = ex[0]*p13[0] + ex[1]*p13[1] + ex[2]*p13[2]; //Now create a vector along the x axis that represents the x component of p13. float iex[3] = { ex[0]*i, ex[1]*i, ex[2]*i }; //Now subtract the X component away from the original vector leaving only the Y component. We use the //variable that will be the unit vector after we scale it. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2]}; //The magnitude of Y component float j = sqrt(sq(ey[0]) + sq(ey[1]) + sq(ey[2])); //Now make vector a unit vector ey[0] /= j; ey[1] /= j; ey[2] /= j; //The cross product of the unit x and y is the unit z //float[] ez = vectorCrossProd(ex, ey); float ez[3] = { ex[1]*ey[2] - ex[2]*ey[1], ex[2]*ey[0] - ex[0]*ey[2], ex[0]*ey[1] - ex[1]*ey[0] }; //Now we have the d, i and j values defined in Wikipedia. //We can plug them into the equations defined in //Wikipedia for Xnew, Ynew and Znew float Xnew = (delta_diagonal_rod_2_tower_1 - delta_diagonal_rod_2_tower_2 + d*d)/(d*2); float Ynew = ((delta_diagonal_rod_2_tower_1 - delta_diagonal_rod_2_tower_3 + i*i + j*j)/2 - i*Xnew) /j; float Znew = sqrt(delta_diagonal_rod_2_tower_1 - Xnew*Xnew - Ynew*Ynew); //Now we can start from the origin in the old coords and //add vectors in the old coords that represent the //Xnew, Ynew and Znew to find the point in the old system cartesian_position[X_AXIS] = delta_tower1_x + ex[0]*Xnew + ey[0]*Ynew - ez[0]*Znew; cartesian_position[Y_AXIS] = delta_tower1_y + ex[1]*Xnew + ey[1]*Ynew - ez[1]*Znew; cartesian_position[Z_AXIS] = z1 + ex[2]*Xnew + ey[2]*Ynew - ez[2]*Znew; }; void forward_kinematics_DELTA(float point[3]) { forward_kinematics_DELTA(point[X_AXIS], point[Y_AXIS], point[Z_AXIS]); } void set_cartesian_from_steppers() { forward_kinematics_DELTA(stepper.get_axis_position_mm(X_AXIS), stepper.get_axis_position_mm(Y_AXIS), stepper.get_axis_position_mm(Z_AXIS)); } #if ENABLED(AUTO_BED_LEVELING_FEATURE) // Adjust print surface height by linear interpolation over the bed_level array. void adjust_delta(float cartesian[3]) { if (delta_grid_spacing[0] == 0 || delta_grid_spacing[1] == 0) return; // G29 not done! int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2; float h1 = 0.001 - half, h2 = half - 0.001, grid_x = max(h1, min(h2, RAW_X_POSITION(cartesian[X_AXIS]) / delta_grid_spacing[0])), grid_y = max(h1, min(h2, RAW_Y_POSITION(cartesian[Y_AXIS]) / delta_grid_spacing[1])); int floor_x = floor(grid_x), floor_y = floor(grid_y); float ratio_x = grid_x - floor_x, ratio_y = grid_y - floor_y, z1 = bed_level[floor_x + half][floor_y + half], z2 = bed_level[floor_x + half][floor_y + half + 1], z3 = bed_level[floor_x + half + 1][floor_y + half], z4 = bed_level[floor_x + half + 1][floor_y + half + 1], left = (1 - ratio_y) * z1 + ratio_y * z2, right = (1 - ratio_y) * z3 + ratio_y * z4, offset = (1 - ratio_x) * left + ratio_x * right; delta[X_AXIS] += offset; delta[Y_AXIS] += offset; delta[Z_AXIS] += offset; /** SERIAL_ECHOPGM("grid_x="); SERIAL_ECHO(grid_x); SERIAL_ECHOPGM(" grid_y="); SERIAL_ECHO(grid_y); SERIAL_ECHOPGM(" floor_x="); SERIAL_ECHO(floor_x); SERIAL_ECHOPGM(" floor_y="); SERIAL_ECHO(floor_y); SERIAL_ECHOPGM(" ratio_x="); SERIAL_ECHO(ratio_x); SERIAL_ECHOPGM(" ratio_y="); SERIAL_ECHO(ratio_y); SERIAL_ECHOPGM(" z1="); SERIAL_ECHO(z1); SERIAL_ECHOPGM(" z2="); SERIAL_ECHO(z2); SERIAL_ECHOPGM(" z3="); SERIAL_ECHO(z3); SERIAL_ECHOPGM(" z4="); SERIAL_ECHO(z4); SERIAL_ECHOPGM(" left="); SERIAL_ECHO(left); SERIAL_ECHOPGM(" right="); SERIAL_ECHO(right); SERIAL_ECHOPGM(" offset="); SERIAL_ECHOLN(offset); */ } #endif // AUTO_BED_LEVELING_FEATURE #endif // DELTA void set_current_from_steppers_for_axis(AxisEnum axis) { #if ENABLED(DELTA) set_cartesian_from_steppers(); current_position[axis] = LOGICAL_POSITION(cartesian_position[axis], axis); #elif ENABLED(AUTO_BED_LEVELING_FEATURE) vector_3 pos = planner.adjusted_position(); current_position[axis] = axis == X_AXIS ? pos.x : axis == Y_AXIS ? pos.y : pos.z; #else current_position[axis] = stepper.get_axis_position_mm(axis); // CORE handled transparently #endif } #if ENABLED(MESH_BED_LEVELING) // This function is used to split lines on mesh borders so each segment is only part of one mesh area void mesh_line_to_destination(float fr_mm_m, uint8_t x_splits = 0xff, uint8_t y_splits = 0xff) { int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X_AXIS)), cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y_AXIS)), cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])), cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS])); NOMORE(cx1, MESH_NUM_X_POINTS - 2); NOMORE(cy1, MESH_NUM_Y_POINTS - 2); NOMORE(cx2, MESH_NUM_X_POINTS - 2); NOMORE(cy2, MESH_NUM_Y_POINTS - 2); if (cx1 == cx2 && cy1 == cy2) { // Start and end on same mesh square line_to_destination(fr_mm_m); set_current_to_destination(); return; } #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist) float normalized_dist, end[NUM_AXIS]; // Split at the left/front border of the right/top square int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2); if (cx2 != cx1 && TEST(x_splits, gcx)) { memcpy(end, destination, sizeof(end)); destination[X_AXIS] = LOGICAL_X_POSITION(mbl.get_probe_x(gcx)); normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]); destination[Y_AXIS] = MBL_SEGMENT_END(Y); CBI(x_splits, gcx); } else if (cy2 != cy1 && TEST(y_splits, gcy)) { memcpy(end, destination, sizeof(end)); destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.get_probe_y(gcy)); normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]); destination[X_AXIS] = MBL_SEGMENT_END(X); CBI(y_splits, gcy); } else { // Already split on a border line_to_destination(fr_mm_m); set_current_to_destination(); return; } destination[Z_AXIS] = MBL_SEGMENT_END(Z); destination[E_AXIS] = MBL_SEGMENT_END(E); // Do the split and look for more borders mesh_line_to_destination(fr_mm_m, x_splits, y_splits); // Restore destination from stack memcpy(destination, end, sizeof(end)); mesh_line_to_destination(fr_mm_m, x_splits, y_splits); } #endif // MESH_BED_LEVELING #if ENABLED(DELTA) || ENABLED(SCARA) inline bool prepare_kinematic_move_to(float target[NUM_AXIS]) { float difference[NUM_AXIS]; LOOP_XYZE(i) difference[i] = target[i] - current_position[i]; float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS])); if (cartesian_mm < 0.000001) cartesian_mm = abs(difference[E_AXIS]); if (cartesian_mm < 0.000001) return false; float _feedrate_mm_s = MMM_TO_MMS_SCALED(feedrate_mm_m); float seconds = cartesian_mm / _feedrate_mm_s; int steps = max(1, int(delta_segments_per_second * seconds)); float inv_steps = 1.0/steps; // SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm); // SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds); // SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps); for (int s = 1; s <= steps; s++) { float fraction = float(s) * inv_steps; LOOP_XYZE(i) target[i] = current_position[i] + difference[i] * fraction; inverse_kinematics(target); #if ENABLED(DELTA) && ENABLED(AUTO_BED_LEVELING_FEATURE) if (!bed_leveling_in_progress) adjust_delta(target); #endif //DEBUG_POS("prepare_kinematic_move_to", target); //DEBUG_POS("prepare_kinematic_move_to", delta); planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], _feedrate_mm_s, active_extruder); } return true; } #endif // DELTA || SCARA #if ENABLED(DUAL_X_CARRIAGE) inline bool prepare_move_to_destination_dualx() { if (active_extruder_parked) { if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) { // move duplicate extruder into correct duplication position. planner.set_position_mm( LOGICAL_X_POSITION(inactive_extruder_x_pos), current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS] ); planner.buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], planner.max_feedrate_mm_s[X_AXIS], 1); SYNC_PLAN_POSITION_KINEMATIC(); stepper.synchronize(); extruder_duplication_enabled = true; active_extruder_parked = false; } else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { // handle unparking of head if (current_position[E_AXIS] == destination[E_AXIS]) { // This is a travel move (with no extrusion) // Skip it, but keep track of the current position // (so it can be used as the start of the next non-travel move) if (delayed_move_time != 0xFFFFFFFFUL) { set_current_to_destination(); NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]); delayed_move_time = millis(); return false; } } delayed_move_time = 0; // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower planner.buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], planner.max_feedrate_mm_s[Z_AXIS], active_extruder); planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], PLANNER_XY_FEEDRATE(), active_extruder); planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], planner.max_feedrate_mm_s[Z_AXIS], active_extruder); active_extruder_parked = false; } } return true; } #endif // DUAL_X_CARRIAGE #if DISABLED(DELTA) && DISABLED(SCARA) inline bool prepare_move_to_destination_cartesian() { // Do not use feedrate_percentage for E or Z only moves if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) { line_to_destination(); } else { #if ENABLED(MESH_BED_LEVELING) if (mbl.active()) { mesh_line_to_destination(MMM_SCALED(feedrate_mm_m)); return false; } else #endif line_to_destination(MMM_SCALED(feedrate_mm_m)); } return true; } #endif // !DELTA && !SCARA #if ENABLED(PREVENT_DANGEROUS_EXTRUDE) inline void prevent_dangerous_extrude(float& curr_e, float& dest_e) { if (DEBUGGING(DRYRUN)) return; float de = dest_e - curr_e; if (de) { if (thermalManager.tooColdToExtrude(active_extruder)) { curr_e = dest_e; // Behave as if the move really took place, but ignore E part SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP); } #if ENABLED(PREVENT_LENGTHY_EXTRUDE) if (labs(de) > EXTRUDE_MAXLENGTH) { curr_e = dest_e; // Behave as if the move really took place, but ignore E part SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP); } #endif } } #endif // PREVENT_DANGEROUS_EXTRUDE /** * Prepare a single move and get ready for the next one * * (This may call planner.buffer_line several times to put * smaller moves into the planner for DELTA or SCARA.) */ void prepare_move_to_destination() { clamp_to_software_endstops(destination); refresh_cmd_timeout(); #if ENABLED(PREVENT_DANGEROUS_EXTRUDE) prevent_dangerous_extrude(current_position[E_AXIS], destination[E_AXIS]); #endif #if ENABLED(DELTA) || ENABLED(SCARA) if (!prepare_kinematic_move_to(destination)) return; #else #if ENABLED(DUAL_X_CARRIAGE) if (!prepare_move_to_destination_dualx()) return; #endif if (!prepare_move_to_destination_cartesian()) return; #endif set_current_to_destination(); } #if ENABLED(ARC_SUPPORT) /** * Plan an arc in 2 dimensions * * The arc is approximated by generating many small linear segments. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm) * Arcs should only be made relatively large (over 5mm), as larger arcs with * larger segments will tend to be more efficient. Your slicer should have * options for G2/G3 arc generation. In future these options may be GCode tunable. */ void plan_arc( float target[NUM_AXIS], // Destination position float* offset, // Center of rotation relative to current_position uint8_t clockwise // Clockwise? ) { float radius = HYPOT(offset[X_AXIS], offset[Y_AXIS]), center_X = current_position[X_AXIS] + offset[X_AXIS], center_Y = current_position[Y_AXIS] + offset[Y_AXIS], linear_travel = target[Z_AXIS] - current_position[Z_AXIS], extruder_travel = target[E_AXIS] - current_position[E_AXIS], r_X = -offset[X_AXIS], // Radius vector from center to current location r_Y = -offset[Y_AXIS], rt_X = target[X_AXIS] - center_X, rt_Y = target[Y_AXIS] - center_Y; // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required. float angular_travel = atan2(r_X * rt_Y - r_Y * rt_X, r_X * rt_X + r_Y * rt_Y); if (angular_travel < 0) angular_travel += RADIANS(360); if (clockwise) angular_travel -= RADIANS(360); // Make a circle if the angular rotation is 0 if (angular_travel == 0 && current_position[X_AXIS] == target[X_AXIS] && current_position[Y_AXIS] == target[Y_AXIS]) angular_travel += RADIANS(360); float mm_of_travel = HYPOT(angular_travel * radius, fabs(linear_travel)); if (mm_of_travel < 0.001) return; uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT)); if (segments == 0) segments = 1; float theta_per_segment = angular_travel / segments; float linear_per_segment = linear_travel / segments; float extruder_per_segment = extruder_travel / segments; /** * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector, * and phi is the angle of rotation. Based on the solution approach by Jens Geisler. * r_T = [cos(phi) -sin(phi); * sin(phi) cos(phi] * r ; * * For arc generation, the center of the circle is the axis of rotation and the radius vector is * defined from the circle center to the initial position. Each line segment is formed by successive * vector rotations. This requires only two cos() and sin() computations to form the rotation * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since * all double numbers are single precision on the Arduino. (True double precision will not have * round off issues for CNC applications.) Single precision error can accumulate to be greater than * tool precision in some cases. Therefore, arc path correction is implemented. * * Small angle approximation may be used to reduce computation overhead further. This approximation * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words, * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an * issue for CNC machines with the single precision Arduino calculations. * * This approximation also allows plan_arc to immediately insert a line segment into the planner * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead. * This is important when there are successive arc motions. */ // Vector rotation matrix values float cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation float sin_T = theta_per_segment; float arc_target[NUM_AXIS]; float sin_Ti, cos_Ti, r_new_Y; uint16_t i; int8_t count = 0; // Initialize the linear axis arc_target[Z_AXIS] = current_position[Z_AXIS]; // Initialize the extruder axis arc_target[E_AXIS] = current_position[E_AXIS]; float fr_mm_s = MMM_TO_MMS_SCALED(feedrate_mm_m); millis_t next_idle_ms = millis() + 200UL; for (i = 1; i < segments; i++) { // Iterate (segments-1) times thermalManager.manage_heater(); millis_t now = millis(); if (ELAPSED(now, next_idle_ms)) { next_idle_ms = now + 200UL; idle(); } if (++count < N_ARC_CORRECTION) { // Apply vector rotation matrix to previous r_X / 1 r_new_Y = r_X * sin_T + r_Y * cos_T; r_X = r_X * cos_T - r_Y * sin_T; r_Y = r_new_Y; } else { // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments. // Compute exact location by applying transformation matrix from initial radius vector(=-offset). // To reduce stuttering, the sin and cos could be computed at different times. // For now, compute both at the same time. cos_Ti = cos(i * theta_per_segment); sin_Ti = sin(i * theta_per_segment); r_X = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti; r_Y = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti; count = 0; } // Update arc_target location arc_target[X_AXIS] = center_X + r_X; arc_target[Y_AXIS] = center_Y + r_Y; arc_target[Z_AXIS] += linear_per_segment; arc_target[E_AXIS] += extruder_per_segment; clamp_to_software_endstops(arc_target); #if ENABLED(DELTA) || ENABLED(SCARA) inverse_kinematics(arc_target); #if ENABLED(DELTA) && ENABLED(AUTO_BED_LEVELING_FEATURE) adjust_delta(arc_target); #endif planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], arc_target[E_AXIS], fr_mm_s, active_extruder); #else planner.buffer_line(arc_target[X_AXIS], arc_target[Y_AXIS], arc_target[Z_AXIS], arc_target[E_AXIS], fr_mm_s, active_extruder); #endif } // Ensure last segment arrives at target location. #if ENABLED(DELTA) || ENABLED(SCARA) inverse_kinematics(target); #if ENABLED(DELTA) && ENABLED(AUTO_BED_LEVELING_FEATURE) adjust_delta(target); #endif planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], fr_mm_s, active_extruder); #else planner.buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], fr_mm_s, active_extruder); #endif // As far as the parser is concerned, the position is now == target. In reality the // motion control system might still be processing the action and the real tool position // in any intermediate location. set_current_to_destination(); } #endif #if ENABLED(BEZIER_CURVE_SUPPORT) void plan_cubic_move(const float offset[4]) { cubic_b_spline(current_position, destination, offset, MMM_TO_MMS_SCALED(feedrate_mm_m), active_extruder); // As far as the parser is concerned, the position is now == target. In reality the // motion control system might still be processing the action and the real tool position // in any intermediate location. set_current_to_destination(); } #endif // BEZIER_CURVE_SUPPORT #if HAS_CONTROLLERFAN void controllerFan() { static millis_t lastMotorOn = 0; // Last time a motor was turned on static millis_t nextMotorCheck = 0; // Last time the state was checked millis_t ms = millis(); if (ELAPSED(ms, nextMotorCheck)) { nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || thermalManager.soft_pwm_bed > 0 || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled... #if E_STEPPERS > 1 || E1_ENABLE_READ == E_ENABLE_ON #if HAS_X2_ENABLE || X2_ENABLE_READ == X_ENABLE_ON #endif #if E_STEPPERS > 2 || E2_ENABLE_READ == E_ENABLE_ON #if E_STEPPERS > 3 || E3_ENABLE_READ == E_ENABLE_ON #endif #endif #endif ) { lastMotorOn = ms; //... set time to NOW so the fan will turn on } // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED; // allows digital or PWM fan output to be used (see M42 handling) digitalWrite(CONTROLLERFAN_PIN, speed); analogWrite(CONTROLLERFAN_PIN, speed); } } #endif // HAS_CONTROLLERFAN #if ENABLED(SCARA) void forward_kinematics_SCARA(float f_scara[3]) { // Perform forward kinematics, and place results in delta[3] // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014 float x_sin, x_cos, y_sin, y_cos; //SERIAL_ECHOPGM("f_delta x="); SERIAL_ECHO(f_scara[X_AXIS]); //SERIAL_ECHOPGM(" y="); SERIAL_ECHO(f_scara[Y_AXIS]); x_sin = sin(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1; x_cos = cos(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1; y_sin = sin(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2; y_cos = cos(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2; //SERIAL_ECHOPGM(" x_sin="); SERIAL_ECHO(x_sin); //SERIAL_ECHOPGM(" x_cos="); SERIAL_ECHO(x_cos); //SERIAL_ECHOPGM(" y_sin="); SERIAL_ECHO(y_sin); //SERIAL_ECHOPGM(" y_cos="); SERIAL_ECHOLN(y_cos); delta[X_AXIS] = x_cos + y_cos + SCARA_offset_x; //theta delta[Y_AXIS] = x_sin + y_sin + SCARA_offset_y; //theta+phi //SERIAL_ECHOPGM(" delta[X_AXIS]="); SERIAL_ECHO(delta[X_AXIS]); //SERIAL_ECHOPGM(" delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]); } void inverse_kinematics(const float cartesian[3]) { // Inverse kinematics. // Perform SCARA IK and place results in delta[3]. // The maths and first version were done by QHARLEY. // Integrated, tweaked by Joachim Cerny in June 2014. float SCARA_pos[2]; static float SCARA_C2, SCARA_S2, SCARA_K1, SCARA_K2, SCARA_theta, SCARA_psi; SCARA_pos[X_AXIS] = RAW_X_POSITION(cartesian[X_AXIS]) * axis_scaling[X_AXIS] - SCARA_offset_x; //Translate SCARA to standard X Y SCARA_pos[Y_AXIS] = RAW_Y_POSITION(cartesian[Y_AXIS]) * axis_scaling[Y_AXIS] - SCARA_offset_y; // With scaling factor. #if (Linkage_1 == Linkage_2) SCARA_C2 = ((sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS])) / (2 * (float)L1_2)) - 1; #else SCARA_C2 = (sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - (float)L1_2 - (float)L2_2) / 45000; #endif SCARA_S2 = sqrt(1 - sq(SCARA_C2)); SCARA_K1 = Linkage_1 + Linkage_2 * SCARA_C2; SCARA_K2 = Linkage_2 * SCARA_S2; SCARA_theta = (atan2(SCARA_pos[X_AXIS], SCARA_pos[Y_AXIS]) - atan2(SCARA_K1, SCARA_K2)) * -1; SCARA_psi = atan2(SCARA_S2, SCARA_C2); delta[X_AXIS] = SCARA_theta * SCARA_RAD2DEG; // Multiply by 180/Pi - theta is support arm angle delta[Y_AXIS] = (SCARA_theta + SCARA_psi) * SCARA_RAD2DEG; // - equal to sub arm angle (inverted motor) delta[Z_AXIS] = RAW_Z_POSITION(cartesian[Z_AXIS]); /** SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]); SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]); SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]); SERIAL_ECHOPGM("scara x="); SERIAL_ECHO(SCARA_pos[X_AXIS]); SERIAL_ECHOPGM(" y="); SERIAL_ECHOLN(SCARA_pos[Y_AXIS]); SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]); SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]); SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]); SERIAL_ECHOPGM("C2="); SERIAL_ECHO(SCARA_C2); SERIAL_ECHOPGM(" S2="); SERIAL_ECHO(SCARA_S2); SERIAL_ECHOPGM(" Theta="); SERIAL_ECHO(SCARA_theta); SERIAL_ECHOPGM(" Psi="); SERIAL_ECHOLN(SCARA_psi); SERIAL_EOL; */ } #endif // SCARA #if ENABLED(TEMP_STAT_LEDS) static bool red_led = false; static millis_t next_status_led_update_ms = 0; void handle_status_leds(void) { float max_temp = 0.0; if (ELAPSED(millis(), next_status_led_update_ms)) { next_status_led_update_ms += 500; // Update every 0.5s HOTEND_LOOP() { max_temp = max(max(max_temp, thermalManager.degHotend(e)), thermalManager.degTargetHotend(e)); } #if HAS_TEMP_BED max_temp = max(max(max_temp, thermalManager.degTargetBed()), thermalManager.degBed()); #endif bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led; if (new_led != red_led) { red_led = new_led; digitalWrite(STAT_LED_RED, new_led ? HIGH : LOW); digitalWrite(STAT_LED_BLUE, new_led ? LOW : HIGH); } } } #endif void enable_all_steppers() { enable_x(); enable_y(); enable_z(); enable_e0(); enable_e1(); enable_e2(); enable_e3(); } void disable_all_steppers() { disable_x(); disable_y(); disable_z(); disable_e0(); disable_e1(); disable_e2(); disable_e3(); } /** * Standard idle routine keeps the machine alive */ void idle( #if ENABLED(FILAMENT_CHANGE_FEATURE) bool no_stepper_sleep/*=false*/ #endif ) { lcd_update(); host_keepalive(); manage_inactivity( #if ENABLED(FILAMENT_CHANGE_FEATURE) no_stepper_sleep #endif ); thermalManager.manage_heater(); #if ENABLED(PRINTCOUNTER) print_job_timer.tick(); #endif #if HAS_BUZZER && PIN_EXISTS(BEEPER) buzzer.tick(); #endif } /** * Manage several activities: * - Check for Filament Runout * - Keep the command buffer full * - Check for maximum inactive time between commands * - Check for maximum inactive time between stepper commands * - Check if pin CHDK needs to go LOW * - Check for KILL button held down * - Check for HOME button held down * - Check if cooling fan needs to be switched on * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT) */ void manage_inactivity(bool ignore_stepper_queue/*=false*/) { #if ENABLED(FILAMENT_RUNOUT_SENSOR) if ((IS_SD_PRINTING || print_job_timer.isRunning()) && !(READ(FIL_RUNOUT_PIN) ^ FIL_RUNOUT_INVERTING)) handle_filament_runout(); if ((IS_SD_PRINTING || print_job_timer.isRunning()) && !(READ(FIL_1_RUNOUT_PIN) ^ FIL_RUNOUT_INVERTING)) handle_filament_runout(); if ((IS_SD_PRINTING || print_job_timer.isRunning()) && !(READ(FIL_2_RUNOUT_PIN) ^ FIL_RUNOUT_INVERTING)) handle_filament_runout(); if ((IS_SD_PRINTING || print_job_timer.isRunning()) && !(READ(FIL_3_RUNOUT_PIN) ^ FIL_RUNOUT_INVERTING)) handle_filament_runout(); #endif if (commands_in_queue < BUFSIZE) get_available_commands(); millis_t ms = millis(); if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) kill(PSTR(MSG_KILLED)); if (stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time) && !ignore_stepper_queue && !planner.blocks_queued()) { #if ENABLED(DISABLE_INACTIVE_X) disable_x(); #endif #if ENABLED(DISABLE_INACTIVE_Y) disable_y(); #endif #if ENABLED(DISABLE_INACTIVE_Z) disable_z(); #endif #if ENABLED(DISABLE_INACTIVE_E) disable_e0(); disable_e1(); disable_e2(); disable_e3(); #endif } #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH if (chdkActive && PENDING(ms, chdkHigh + CHDK_DELAY)) { chdkActive = false; WRITE(CHDK, LOW); } #endif #if HAS_KILL // Check if the kill button was pressed and wait just in case it was an accidental // key kill key press // ------------------------------------------------------------------------------- static int killCount = 0; // make the inactivity button a bit less responsive const int KILL_DELAY = 750; if (!READ(KILL_PIN)) killCount++; else if (killCount > 0) killCount--; // Exceeded threshold and we can confirm that it was not accidental // KILL the machine // ---------------------------------------------------------------- if (killCount >= KILL_DELAY) kill(PSTR(MSG_KILLED)); #endif #if HAS_HOME // Check to see if we have to home, use poor man's debouncer // --------------------------------------------------------- static int homeDebounceCount = 0; // poor man's debouncing count const int HOME_DEBOUNCE_DELAY = 2500; if (!READ(HOME_PIN)) { if (!homeDebounceCount) { enqueue_and_echo_commands_P(PSTR("G28")); LCD_MESSAGEPGM(MSG_AUTO_HOME); } if (homeDebounceCount < HOME_DEBOUNCE_DELAY) homeDebounceCount++; else homeDebounceCount = 0; } #endif #if HAS_CONTROLLERFAN controllerFan(); // Check if fan should be turned on to cool stepper drivers down #endif #if ENABLED(EXTRUDER_RUNOUT_PREVENT) if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL) && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) { #if ENABLED(SWITCHING_EXTRUDER) bool oldstatus = E0_ENABLE_READ; enable_e0(); #else // !SWITCHING_EXTRUDER bool oldstatus; switch (active_extruder) { case 0: oldstatus = E0_ENABLE_READ; enable_e0(); break; #if E_STEPPERS > 1 case 1: oldstatus = E1_ENABLE_READ; enable_e1(); break; #if E_STEPPERS > 2 case 2: oldstatus = E2_ENABLE_READ; enable_e2(); break; #if E_STEPPERS > 3 case 3: oldstatus = E3_ENABLE_READ; enable_e3(); break; #endif #endif #endif } #endif // !SWITCHING_EXTRUDER float oldepos = current_position[E_AXIS], oldedes = destination[E_AXIS]; planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS] + (EXTRUDER_RUNOUT_EXTRUDE) * (EXTRUDER_RUNOUT_ESTEPS) / planner.axis_steps_per_mm[E_AXIS], MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED) * (EXTRUDER_RUNOUT_ESTEPS) / planner.axis_steps_per_mm[E_AXIS], active_extruder); current_position[E_AXIS] = oldepos; destination[E_AXIS] = oldedes; planner.set_e_position_mm(oldepos); previous_cmd_ms = ms; // refresh_cmd_timeout() stepper.synchronize(); #if ENABLED(SWITCHING_EXTRUDER) E0_ENABLE_WRITE(oldstatus); #else switch (active_extruder) { case 0: E0_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 1 case 1: E1_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 2 case 2: E2_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 3 case 3: E3_ENABLE_WRITE(oldstatus); break; #endif #endif #endif } #endif // !SWITCHING_EXTRUDER } #endif // EXTRUDER_RUNOUT_PREVENT #if ENABLED(DUAL_X_CARRIAGE) // handle delayed move timeout if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) { // travel moves have been received so enact them delayed_move_time = 0xFFFFFFFFUL; // force moves to be done set_destination_to_current(); prepare_move_to_destination(); } #endif #if ENABLED(TEMP_STAT_LEDS) handle_status_leds(); #endif planner.check_axes_activity(); } void kill(const char* lcd_msg) { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_KILLED); #if ENABLED(ULTRA_LCD) kill_screen(lcd_msg); #else UNUSED(lcd_msg); #endif for (int i = 5; i--;) delay(100); // Wait a short time cli(); // Stop interrupts thermalManager.disable_all_heaters(); disable_all_steppers(); #if HAS_POWER_SWITCH pinMode(PS_ON_PIN, INPUT); #endif suicide(); while (1) { #if ENABLED(USE_WATCHDOG) watchdog_reset(); #endif } // Wait for reset } #if ENABLED(FILAMENT_RUNOUT_SENSOR) void handle_filament_runout() { if (!filament_ran_out) { filament_ran_out = true; enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT)); stepper.synchronize(); } } #endif // FILAMENT_RUNOUT_SENSOR #if ENABLED(FAST_PWM_FAN) void setPwmFrequency(uint8_t pin, int val) { val &= 0x07; switch (digitalPinToTimer(pin)) { #if defined(TCCR0A) case TIMER0A: case TIMER0B: // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02)); // TCCR0B |= val; break; #endif #if defined(TCCR1A) case TIMER1A: case TIMER1B: // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12)); // TCCR1B |= val; break; #endif #if defined(TCCR2) case TIMER2: case TIMER2: TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12)); TCCR2 |= val; break; #endif #if defined(TCCR2A) case TIMER2A: case TIMER2B: TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22)); TCCR2B |= val; break; #endif #if defined(TCCR3A) case TIMER3A: case TIMER3B: case TIMER3C: TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32)); TCCR3B |= val; break; #endif #if defined(TCCR4A) case TIMER4A: case TIMER4B: case TIMER4C: TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42)); TCCR4B |= val; break; #endif #if defined(TCCR5A) case TIMER5A: case TIMER5B: case TIMER5C: TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52)); TCCR5B |= val; break; #endif } } #endif // FAST_PWM_FAN void stop() { thermalManager.disable_all_heaters(); if (IsRunning()) { Running = false; Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); LCD_MESSAGEPGM(MSG_STOPPED); } } float calculate_volumetric_multiplier(float diameter) { if (!volumetric_enabled || diameter == 0) return 1.0; float d2 = diameter * 0.5; return 1.0 / (M_PI * d2 * d2); } void calculate_volumetric_multipliers() { for (uint8_t i = 0; i < COUNT(filament_size); i++) volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]); }
[ "tangqi@yuenjee.com" ]
tangqi@yuenjee.com
2da9da095a7804e4f4b630b3f93ef30a99db88fb
fd6b7aa209a8ba367e1749f22a0cf3d9ee0a5b8f
/enkov_example.ino
1de55f9af5e4d53862cba86b103ccddc08d1b351
[]
no_license
claytonjeanette/enikovGui
7227e6e90f3e4b4b115b53899668e7f8a097bcf1
115c669f5afa24651fbe697b0531a54bdfa3ae76
refs/heads/master
2016-09-12T22:39:53.501313
2016-05-19T01:40:10
2016-05-19T01:40:10
57,937,269
0
0
null
null
null
null
UTF-8
C++
false
false
1,675
ino
#include <SparkFunAutoDriver.h> #include <SPI.h> #include "SparkFunnotes.h" // Test sketch for the L6470 AutoDriver library. This program instantiates three // AutoDriver boards and uses them to play Jonathon Coulton's "Want You Gone" from // the Portal 2 soundtrack. In a more general sense, it adds support for playing // music with stepper motors. Not all notes can be played, of course- at too high // a steps/sec rate, the motors will slip and dogs and cats will live together. // Create our AutoDriver instances. The parameters are pin numbers in // Arduino-speke for CS and reset. A third parameter could be passed for // a busy pin, but we're not using that here. AutoDriver boardA(10, 6); // Spinneret AutoDriver boardB(9, 6); //Forward Back AutoDriver boardC(5, 6); //Left Right AutoDriver boardD(3, 6); // Up Down AutoDriver boardE(8, 6); //DC motor void setup() { Serial.begin(9600); Serial.println("Hello world"); dSPINConfig(); } // loop() waits for a character- any character- and then plays the song. void loop() { if (Serial.available() !=0) { int input = Serial.read(); if(input == 'F'){ forward_z(); Serial.println("F"); } if(input == 'B'){ back_z(); Serial.println("B"); } if(input == 'L'){ left_x(); Serial.println("Left"); } if(input == 'R'){ right_x(); Serial.println("Right"); } if(input == 'U'){ up_y(); Serial.println("UP/Down"); } if(input == 'S'){ dc_fwd(); Serial.println("FWD"); } else{ dummy(); } Serial.println("Play it!"); // wantYouGone(); Serial.println("Done playing!"); } }
[ "cjeanette@email.arizona.edu" ]
cjeanette@email.arizona.edu
b95da96b345daf39e2fde2514327d5aae260dece
83f0b29cbd5ac6a207da7e8831a7771f5bf9a659
/RaTGL/PropertiesView.cpp
cdadad56f91e1d2ea181a7b48d4dbe27fc6e4d5e
[]
no_license
edikoz/RaTGL
da322b3134e27de8afb5b5814291ac52cfdd6287
9550c81887a2a29a2cb08b8482e38b8e7d76508a
refs/heads/master
2020-06-12T21:16:38.024819
2020-02-20T19:53:12
2020-02-20T19:53:12
194,420,598
0
0
null
null
null
null
UTF-8
C++
false
false
5,677
cpp
#include "stdafx.h" #include "PropertiesView.h" #include "resource.h" #include "ShaderText.h" #include "PropertyView.h" PropertiesView *PropertiesView::propertiesView = nullptr; LRESULT CALLBACK PropertiesView::handleMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { tagSCROLLINFO si; switch (message) { case WM_ERASEBKGND: { HDC hdc = (HDC)wParam; RECT rc; HBRUSH white = (HBRUSH)GetStockObject(WHITE_BRUSH); GetClientRect(hWnd, &rc); FillRect(hdc, &rc, white); return 1L; } case WM_CREATE: si = { sizeof(SCROLLINFO), SIF_ALL, 0, 1, 1, 0, 0 }; SetScrollInfo(hWnd, SB_VERT, &si, TRUE); return 0; case WM_VSCROLL: si.cbSize = sizeof(si); si.fMask = SIF_ALL; GetScrollInfo(hWnd, SB_VERT, &si); switch (LOWORD(wParam)) { case SB_LINEUP: si.nPos -= 1; break; case SB_LINEDOWN: si.nPos += 1; break; case SB_PAGEUP: si.nPos -= si.nPage; break; case SB_PAGEDOWN: si.nPos += si.nPage; break; case SB_THUMBTRACK: si.nPos = si.nTrackPos; break; } propertiesView->scrollY = -si.nPos; si.fMask = SIF_POS; SetScrollInfo(hWnd, SB_VERT, &si, TRUE); GetScrollInfo(hWnd, SB_VERT, &si); propertiesView->updateElements(); return 0; case WM_DESTROY: DeleteObject(propertiesView->hFont); return 0; default: return DefWindowProc(hWnd, message, wParam, lParam); } } bool PropertiesView::isFirst(std::list<RaTElement*> *l, RaTElement *cmp) { return cmp == l->front(); } bool PropertiesView::isLast(std::list<RaTElement*> *l, RaTElement *cmp) { return cmp == l->back(); } void PropertiesView::clearElements() { for (auto v : elements) delete v; elements.clear(); elements.push_back(new EmitterElement(0.0f, 0.0f, 100, 100, 5.0f, 5.0f, 1)); elements.push_back(new LensElement(LensElement::SPHERE, 10.0f, 0.0f, 0.0f, 0.0f, 0.0f, 20.0f, 0.5f, -20.0f, {0.0f})); elements.push_back(new LensElement(LensElement::SPHERE, 80.0f, 0.0f, 0.0f, 0.0f, 0.0f, 20.0f, 2.0f, 20.0f, {0.0f})); elements.push_back(new CameraElement(10.0f, 0.0f, 0.0f, 10.0f, 10.0f, 128, 128)); update(); generate(); } void PropertiesView::generate() { generateShader(); Shader::InitRays(nullptr, 0); generateBuffer(); } void PropertiesView::resize(int w, int h) { dims.w = w; dims.h = h; update(); } void PropertiesView::update() { updateScroll(); updateElements(); } void PropertiesView::updateScroll() { int H = 0; for (RaTElement *e : elements) H += e->getH(); if (dims.h < H) { if (H + scrollY < dims.h) scrollY = dims.h - H; ShowScrollBar(hwnd, SB_VERT, TRUE); tagSCROLLINFO si; si = { sizeof(SCROLLINFO), SIF_RANGE, 0, H - dims.h, 1, 0, 0 }; SetScrollInfo(hwnd, SB_VERT, &si, TRUE); } else { scrollY = 0; ShowScrollBar(hwnd, SB_VERT, FALSE); if (IsThemeActive()) { SetWindowTheme(hwnd, NULL, NULL); UpdateWindow(hwnd); } } } void PropertiesView::updateElements() { int elemY = scrollY; for(auto it=elements.begin(); it!=elements.end(); it++) { (*it)->setIterToSelf(it); (*it)->resize(elemY, dims.w); elemY += (*it)->getH(); } } void PropertiesView::generateShader() { ShaderText::empty(); //TODO: replace shaderRT to ray_traces std::string shaderRT = ""; for (RaTElement *e : elements) shaderRT += e->getShader(); if (ShaderText::rays.length()) ShaderText::rays.pop_back(); std::string shader_RaT = replaceString(ShaderText::shdrMain, "REPLACE_UNIFORMS", ShaderText::uniforms); shader_RaT = replaceString(shader_RaT, "REPLACE_CONSTS", ShaderText::consts); shader_RaT = replaceString(shader_RaT, "RAYS", ShaderText::rays); shader_RaT = replaceString(shader_RaT, "REPLACE_FUNCTIONS", ShaderText::shdrFunctions); shader_RaT = replaceString(shader_RaT, "REPLACE_RAY_TRACE", shaderRT); shader_RaT = replaceString(shader_RaT, "REPLACE_EMIT", ShaderText::emits); shader_RaT = replaceString(shader_RaT, "REPLACE_CHECK", ShaderText::conditions); shader_RaT = replaceString(shader_RaT, "MAX_VERTICES", std::to_string(ShaderText::vertices_count)); std::ofstream shaderFile("Res/Shaders/line.gsr", std::ios::out | std::ios_base::beg); if (shaderFile.is_open()) shaderFile << shader_RaT; shaderFile.close(); } void PropertiesView::generateBuffer() { for (RaTElement *e : elements){ e->releaseGLresources(); e->obtainGLresources(); } } void PropertiesView::drawElements(Camera *camera) { std::list<RaTElement*> sorted = propertiesView->elements; for (RaTElement *e : sorted) e->calcDistanceTo(camera->getPos()); sorted.sort(RaTElement::cmpDistance); for (RaTElement *e : sorted) e->draw(camera); } int PropertiesView::getNumDots() { return elements.size(); } EmitterElement* PropertiesView::getEmitter() { return static_cast<EmitterElement*>(elements.front()); } CameraElement* PropertiesView::getSensor() { return static_cast<CameraElement*>(elements.back()); } PropertiesView::PropertiesView(HWND parent, Dims dim) : RaTwindow(L"PropertiesView", parent, WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_CLIPCHILDREN, dim), scrollY(0) { propertiesView = this; hFont = CreateFont(14, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI"); int vsw = GetSystemMetrics(SM_CXVSCROLL); dims.w -= vsw; hbmpInsert = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_BITMAP1)); hbmpInsertDisabled = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_BITMAP10)); hbmpDelete = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_BITMAP4)); hbmpDeleteDisabled = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_BITMAP11)); hbmpUnroll = LoadBitmap(hInst, MAKEINTRESOURCEW(IDB_BITMAP7)); hbmpRoll = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_BITMAP9)); RaTElement::regClass(); //clearElements(); }
[ "drawwww@rambler.ru" ]
drawwww@rambler.ru
3d030f1839e9cb6768d7863eb30ab099c7b3840b
c6d7421fbbf10b33ecc20c0824e7fde819ba76cc
/src/esp/scene/SceneGraph.cpp
0fb2428886e004f059fda43faef55eb0fe4b510c
[ "MIT" ]
permissive
rakeshshrestha31/habitat-sim
f56f2156fae74c6f9ea8f0bd53871ccd12220044
5a304163319053ce47e9e31026323df3262f2f64
refs/heads/master
2020-04-29T02:10:38.320884
2019-07-23T00:04:00
2019-07-23T00:04:00
175,755,977
0
0
MIT
2019-03-15T05:41:01
2019-03-15T05:41:00
null
UTF-8
C++
false
false
1,589
cpp
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "SceneGraph.h" #include <Magnum/Math/Algorithms/GramSchmidt.h> namespace esp { namespace scene { SceneGraph::SceneGraph() : rootNode_{world_}, defaultRenderCameraNode_{rootNode_} { defaultRenderCamera_.attach(defaultRenderCameraNode_); } // set transformation and projection matrix to the default camera void SceneGraph::setDefaultRenderCamera(sensor::Sensor& sensor) { ASSERT(sensor.isValid()); ASSERT(sensor.isVisualSensor()); auto* sensorNode = sensor.getSceneNode(); Magnum::Matrix4 T = sensorNode->MagnumObject::absoluteTransformation(); Magnum::Matrix3 R = T.rotationScaling(); Magnum::Math::Algorithms::gramSchmidtOrthonormalizeInPlace(R); VLOG(1) << "||R - GS(R)|| = " << Eigen::Map<mat3f>((R - T.rotationShear()).data()).norm(); T = Magnum::Matrix4::from(R, T.translation()) * Magnum::Matrix4::scaling(T.scaling()); // set the transformation to the default camera // so that the camera has the correct modelview matrix for rendering; // to do it, // obtain the *absolute* transformation from the sensor node, // apply it as the *relative* transformation between the default camera and // its parent, which is rootNode_. defaultRenderCameraNode_.MagnumObject::setTransformation(T); // set the projection matrix to the default camera sensor.setProjectionMatrix(defaultRenderCamera_); } } // namespace scene } // namespace esp
[ "msavva@fb.com" ]
msavva@fb.com
a334e315f3137aac66b14391969531daa898f6a4
00e580809ee65edb00e6c75da8b3c558ba42833d
/seePlusia/Road.hpp
388e875bc78fd001ae00e6398943ad367b1f891a
[]
no_license
barkotefuye/CS056
dc0d9215795759b94bfe1ec3302e25530f359ccd
e4b35ad3a690271bc039b1b758b6d17c4409fa1f
refs/heads/master
2020-04-21T04:25:07.316284
2019-03-04T11:29:15
2019-03-04T11:29:15
169,312,389
1
0
null
null
null
null
UTF-8
C++
false
false
334
hpp
class Road { private: Location *m_a, *m_b; // endpoints of this road. int m_days; // the number of days to travel this road. public: Road(Location*, Location*); // initialize attributes. Location* get_end(Location*); // get the other end of this road. int get_days(); // get the number of days to travel this road. };
[ "barkotefuye@seattleacademy.org" ]
barkotefuye@seattleacademy.org
50adb2f63442e675d66c1d7aad92701530f2522b
04b95d4f9c4d2503d19685c548953c7ca6c7cdf0
/include/Ogre/OgreEdgeListBuilder.h
012410bcd709cc26f7649b4923d7adb608075f73
[ "MIT" ]
permissive
Kanma/Ogre
f3fa67cedab75f30ab6f03d77d12c727a553397f
21bf1fbbfd8ade12d8009c00940e136d78f21bea
refs/heads/master
2021-01-25T06:37:10.501303
2014-05-08T13:07:32
2014-05-08T13:07:32
526,053
0
0
null
null
null
null
UTF-8
C++
false
false
12,161
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __EdgeListBuilder_H__ #define __EdgeListBuilder_H__ #include "OgrePrerequisites.h" #include "OgreVector4.h" #include "OgreHardwareVertexBuffer.h" #include "OgreRenderOperation.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Math * @{ */ /** This class contains the information required to describe the edge connectivity of a given set of vertices and indexes. @remarks This information is built using the EdgeListBuilder class. Note that for a given mesh, which can be made up of multiple submeshes, there are separate edge lists for when */ class _OgreExport EdgeData : public EdgeDataAlloc { public: /** Basic triangle structure. */ struct Triangle { /** The set of indexes this triangle came from (NB it is possible that the triangles on one side of an edge are using a different vertex buffer from those on the other side.) */ size_t indexSet; /** The vertex set these vertices came from. */ size_t vertexSet; size_t vertIndex[3];/// Vertex indexes, relative to the original buffer size_t sharedVertIndex[3]; /// Vertex indexes, relative to a shared vertex buffer with // duplicates eliminated (this buffer is not exposed) Triangle() :indexSet(0), vertexSet(0) {} }; /** Edge data. */ struct Edge { /** The indexes of the 2 tris attached, note that tri 0 is the one where the indexes run _anti_ clockwise along the edge. Indexes must be reversed for tri 1. */ size_t triIndex[2]; /** The vertex indices for this edge. Note that both vertices will be in the vertex set as specified in 'vertexSet', which will also be the same as tri 0 */ size_t vertIndex[2]; /** Vertex indices as used in the shared vertex list, not exposed. */ size_t sharedVertIndex[2]; /** Indicates if this is a degenerate edge, ie it does not have 2 triangles */ bool degenerate; }; // Array of 4D vector of triangle face normal, which is unit vector orthogonal // to the triangles, plus distance from origin. // Use aligned policy here because we are intended to use in SIMD optimised routines . typedef std::vector<Vector4, STLAllocator<Vector4, CategorisedAlignAllocPolicy<MEMCATEGORY_GEOMETRY> > > TriangleFaceNormalList; // Working vector used when calculating the silhouette. // Use std::vector<char> instead of std::vector<bool> which might implemented // similar bit-fields causing loss performance. typedef vector<char>::type TriangleLightFacingList; typedef vector<Triangle>::type TriangleList; typedef vector<Edge>::type EdgeList; /** A group of edges sharing the same vertex data. */ struct EdgeGroup { /** The vertex set index that contains the vertices for this edge group. */ size_t vertexSet; /** Pointer to vertex data used by this edge group. */ const VertexData* vertexData; /** Index to main triangles array, indicate the first triangle of this edge group, and all triangles of this edge group are stored continuous in main triangles array. */ size_t triStart; /** Number triangles of this edge group. */ size_t triCount; /** The edges themselves. */ EdgeList edges; }; typedef vector<EdgeGroup>::type EdgeGroupList; /** Main triangles array, stores all triangles of this edge list. Note that triangles are grouping against edge group. */ TriangleList triangles; /** All triangle face normals. It should be 1:1 with triangles. */ TriangleFaceNormalList triangleFaceNormals; /** Triangle light facing states. It should be 1:1 with triangles. */ TriangleLightFacingList triangleLightFacings; /** All edge groups of this edge list. */ EdgeGroupList edgeGroups; /** Flag indicate the mesh is manifold. */ bool isClosed; /** Calculate the light facing state of the triangles in this edge list @remarks This is normally the first stage of calculating a silhouette, i.e. establishing which tris are facing the light and which are facing away. This state is stored in the 'triangleLightFacings'. @param lightPos 4D position of the light in object space, note that for directional lights (which have no position), the w component is 0 and the x/y/z position are the direction. */ void updateTriangleLightFacing(const Vector4& lightPos); /** Updates the face normals for this edge list based on (changed) position information, useful for animated objects. @param vertexSet The vertex set we are updating @param positionBuffer The updated position buffer, must contain ONLY xyz */ void updateFaceNormals(size_t vertexSet, const HardwareVertexBufferSharedPtr& positionBuffer); // Debugging method void log(Log* log); }; /** General utility class for building edge lists for geometry. @remarks You can add multiple sets of vertex and index data to build and edge list. Edges will be built between the various sets as well as within sets; this allows you to use a model which is built from multiple SubMeshes each using separate index and (optionally) vertex data and still get the same connectivity information. It's important to note that the indexes for the edge will be constrained to a single vertex buffer though (this is required in order to render the edge). */ class _OgreExport EdgeListBuilder { public: EdgeListBuilder(); virtual ~EdgeListBuilder(); /** Add a set of vertex geometry data to the edge builder. @remarks You must add at least one set of vertex data to the builder before invoking the build method. */ void addVertexData(const VertexData* vertexData); /** Add a set of index geometry data to the edge builder. @remarks You must add at least one set of index data to the builder before invoking the build method. @param indexData The index information which describes the triangles. @param vertexSet The vertex data set this index data refers to; you only need to alter this if you have added multiple sets of vertices @param opType The operation type used to render these indexes. Only triangle types are supported (no point or line types) */ void addIndexData(const IndexData* indexData, size_t vertexSet = 0, RenderOperation::OperationType opType = RenderOperation::OT_TRIANGLE_LIST); /** Builds the edge information based on the information built up so far. @remarks The caller takes responsibility for deleting the returned structure. */ EdgeData* build(void); /// Debugging method void log(Log* l); protected: /** A vertex can actually represent several vertices in the final model, because vertices along texture seams etc will have been duplicated. In order to properly evaluate the surface properties, a single common vertex is used for these duplicates, and the faces hold the detail of the duplicated vertices. */ struct CommonVertex { Vector3 position; // location of point in euclidean space size_t index; // place of vertex in common vertex list size_t vertexSet; // The vertex set this came from size_t indexSet; // The index set this was referenced (first) from size_t originalIndex; // place of vertex in original vertex set }; /** A set of indexed geometry data */ struct Geometry { size_t vertexSet; // The vertex data set this geometry data refers to size_t indexSet; // The index data set this geometry data refers to const IndexData* indexData; // The index information which describes the triangles. RenderOperation::OperationType opType; // The operation type used to render this geometry }; /** Comparator for sorting geometries by vertex set */ struct geometryLess { bool operator()(const Geometry& a, const Geometry& b) const { if (a.vertexSet < b.vertexSet) return true; if (a.vertexSet > b.vertexSet) return false; return a.indexSet < b.indexSet; } }; /** Comparator for unique vertex list */ struct vectorLess { bool operator()(const Vector3& a, const Vector3& b) const { if (a.x < b.x) return true; if (a.x > b.x) return false; if (a.y < b.y) return true; if (a.y > b.y) return false; return a.z < b.z; } }; typedef vector<const VertexData*>::type VertexDataList; typedef vector<Geometry>::type GeometryList; typedef vector<CommonVertex>::type CommonVertexList; GeometryList mGeometryList; VertexDataList mVertexDataList; CommonVertexList mVertices; EdgeData* mEdgeData; /// Map for identifying common vertices typedef map<Vector3, size_t, vectorLess>::type CommonVertexMap; CommonVertexMap mCommonVertexMap; /** Edge map, used to connect edges. Note we allow many triangles on an edge, after connected an existing edge, we will remove it and never used again. */ typedef multimap< std::pair<size_t, size_t>, std::pair<size_t, size_t> >::type EdgeMap; EdgeMap mEdgeMap; void buildTrianglesEdges(const Geometry &geometry); /// Finds an existing common vertex, or inserts a new one size_t findOrCreateCommonVertex(const Vector3& vec, size_t vertexSet, size_t indexSet, size_t originalIndex); /// Connect existing edge or create a new edge - utility method during building void connectOrCreateEdge(size_t vertexSet, size_t triangleIndex, size_t vertIndex0, size_t vertIndex1, size_t sharedVertIndex0, size_t sharedVertIndex1); }; /** @} */ /** @} */ } #endif
[ "philip.abbet@gmail.com" ]
philip.abbet@gmail.com
d34ecc3ecaca3d7eee27641bc6f258c01bdec5ea
962d13134dd48d6261e56828c8f69bfb575ff3e7
/kernel/lib/crypto/global_prng.cpp
c9cef94aaa3effb8a88140e245bedb9f0a8fbc14
[]
no_license
saltstar/smartnix
a61295a49450087a7640c76774f15fb38f07e950
8cb77436763db43f70dbe49ea035f5f7e29becac
refs/heads/master
2021-01-17T21:23:58.604835
2019-12-27T01:21:38
2019-12-27T01:21:38
35,830,495
2
0
null
null
null
null
UTF-8
C++
false
false
6,123
cpp
#include <lib/crypto/global_prng.h> #include <assert.h> #include <ctype.h> #include <err.h> #include <explicit-memory/bytes.h> #include <fbl/algorithm.h> #include <kernel/auto_lock.h> #include <kernel/cmdline.h> #include <kernel/mutex.h> #include <lib/crypto/cryptolib.h> #include <lib/crypto/entropy/collector.h> #include <lib/crypto/entropy/hw_rng_collector.h> #include <lib/crypto/entropy/jitterentropy_collector.h> #include <lib/crypto/entropy/quality_test.h> #include <lib/crypto/prng.h> #include <lk/init.h> #include <new> #include <string.h> #include <trace.h> #define LOCAL_TRACE 0 namespace crypto { namespace GlobalPRNG { static PRNG* kGlobalPrng = nullptr; PRNG* GetInstance() { ASSERT(kGlobalPrng); return kGlobalPrng; } // Returns true if the kernel cmdline provided at least PRNG::kMinEntropy bytes // of entropy, and false otherwise. // // TODO(security): Remove this in favor of virtio-rng once it is available and // we decide we don't need it for getting entropy from elsewhere. static bool IntegrateCmdlineEntropy() { const char* entropy = cmdline_get("kernel.entropy-mixin"); if (!entropy) { return false; } const size_t kMaxEntropyArgumentLen = 128; const size_t hex_len = fbl::min(strlen(entropy), kMaxEntropyArgumentLen); for (size_t i = 0; i < hex_len; ++i) { if (!isxdigit(entropy[i])) { panic("Invalid entropy string: idx %zu is not an ASCII hex digit\n", i); } } uint8_t digest[clSHA256_DIGEST_SIZE]; clSHA256(entropy, static_cast<int>(hex_len), digest); kGlobalPrng->AddEntropy(digest, sizeof(digest)); // We have a pointer to const, but it's actually a pointer to the // mutable global state in __kernel_cmdline that is still live (it // will be copied into the userboot bootstrap message later). So // it's fully well-defined to cast away the const and mutate this // here so the bits can't leak to userboot. While we're at it, // prettify the result a bit so it's obvious what one is looking at. mandatory_memset(const_cast<char*>(entropy), 'x', hex_len); if (hex_len >= sizeof(".redacted=") - 1) { memcpy(const_cast<char*>(entropy) - 1, ".redacted=", sizeof(".redacted=") - 1); } const size_t entropy_added = fbl::max(hex_len / 2, sizeof(digest)); LTRACEF("Collected %zu bytes of entropy from the kernel cmdline.\n", entropy_added); return (entropy_added >= PRNG::kMinEntropy); } // Returns true on success, false on failure. static bool SeedFrom(entropy::Collector* collector) { uint8_t buf[PRNG::kMinEntropy] = {0}; size_t remaining = collector->BytesNeeded(8 * PRNG::kMinEntropy); #if LOCAL_TRACE { char name[ZX_MAX_NAME_LEN]; collector->get_name(name, sizeof(name)); LTRACEF("About to collect %zu bytes of entropy from '%s'.\n", remaining, name); } #endif while (remaining > 0) { size_t result = collector->DrawEntropy( buf, fbl::min(sizeof(buf), remaining)); if (result == 0) { LTRACEF("Collected 0 bytes; aborting. " "There were %zu bytes remaining to collect.\n", remaining); return false; } // TODO(ZX-1007): don't assume that every byte of entropy that's added // has a full 8 bits worth of entropy kGlobalPrng->AddEntropy(buf, result); mandatory_memset(buf, 0, sizeof(buf)); remaining -= result; } LTRACEF("Successfully collected entropy.\n"); return true; } // Instantiates the global PRNG (in non-thread-safe mode) and seeds it. static void EarlyBootSeed(uint level) { ASSERT(kGlobalPrng == nullptr); // Before doing anything else, test our entropy collector. This is // explicitly called here rather than in another init hook to ensure // ordering (at level LK_INIT_LEVEL_TARGET_EARLY, but before the rest of // EarlyBootSeed). entropy::EarlyBootTest(); // Statically allocate an array of bytes to put the PRNG into. We do this // to control when the PRNG constructor is called. // TODO(security): This causes the PRNG state to be in a fairly predictable // place. Some aspects of KASLR will help with this, but we may // additionally want to remap where this is later. alignas(alignof(PRNG))static uint8_t prng_space[sizeof(PRNG)]; kGlobalPrng = new (&prng_space) PRNG(nullptr, 0, PRNG::NonThreadSafeTag()); // TODO(security): Have the PRNG reseed based on usage unsigned int successful = 0; // number of successful entropy sources entropy::Collector* collector; if (entropy::HwRngCollector::GetInstance(&collector) == ZX_OK && SeedFrom(collector)) { successful++; } if (entropy::JitterentropyCollector::GetInstance(&collector) == ZX_OK && SeedFrom(collector)) { successful++; } if (IntegrateCmdlineEntropy()) { successful++; } if (successful == 0) { printf("WARNING: System has insufficient randomness. It is completely " "unsafe to use this system for any cryptographic applications." "\n"); // TODO(security): *CRITICAL* This is a fallback for systems without RNG // hardware that we should remove and attempt to do better. If this // fallback is used, it breaks all cryptography used on the system. // *CRITICAL* uint8_t buf[PRNG::kMinEntropy] = {0}; kGlobalPrng->AddEntropy(buf, sizeof(buf)); return; } else { LTRACEF("Successfully collected entropy from %u sources.\n", successful); } } // Migrate the global PRNG to enter thread-safe mode. static void BecomeThreadSafe(uint level) { GetInstance()->BecomeThreadSafe(); } } //namespace GlobalPRNG } // namespace crypto LK_INIT_HOOK(global_prng_seed, crypto::GlobalPRNG::EarlyBootSeed, LK_INIT_LEVEL_TARGET_EARLY); LK_INIT_HOOK(global_prng_thread_safe, crypto::GlobalPRNG::BecomeThreadSafe, LK_INIT_LEVEL_THREADING - 1)
[ "376305680@qq.com" ]
376305680@qq.com
4fdd38a8975b99697b7862d7930fa069cbc5d8ca
52532e524ea325b9938fe3766018d01d8cc79863
/protobuf_gen/include/file_trans.pb.h
e942b1879b63e24adb479c37592cfd13e08220cd
[]
no_license
whiteJadeSoup/MsgSvr
94e660bca66f96e92e5ff646cd1470c661b13b2a
5af0587d22d8ea5f23367f6ca966d48db7c72615
refs/heads/master
2021-05-30T21:33:11.439565
2016-05-02T09:09:46
2016-05-02T09:09:46
null
0
0
null
null
null
null
UTF-8
C++
false
true
9,593
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: file_trans.proto #ifndef PROTOBUF_file_5ftrans_2eproto__INCLUDED #define PROTOBUF_file_5ftrans_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3000000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) namespace IM { // Internal implementation detail -- do not call these. void protobuf_AddDesc_file_5ftrans_2eproto(); void protobuf_AssignDesc_file_5ftrans_2eproto(); void protobuf_ShutdownFile_file_5ftrans_2eproto(); class FileTrans; // =================================================================== class FileTrans : public ::google::protobuf::Message { public: FileTrans(); virtual ~FileTrans(); FileTrans(const FileTrans& from); inline FileTrans& operator=(const FileTrans& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const FileTrans& default_instance(); void Swap(FileTrans* other); // implements Message ---------------------------------------------- inline FileTrans* New() const { return New(NULL); } FileTrans* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const FileTrans& from); void MergeFrom(const FileTrans& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(FileTrans* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional int64 req_id = 1; void clear_req_id(); static const int kReqIdFieldNumber = 1; ::google::protobuf::int64 req_id() const; void set_req_id(::google::protobuf::int64 value); // optional int64 target_id = 2; void clear_target_id(); static const int kTargetIdFieldNumber = 2; ::google::protobuf::int64 target_id() const; void set_target_id(::google::protobuf::int64 value); // optional string name = 3; void clear_name(); static const int kNameFieldNumber = 3; const ::std::string& name() const; void set_name(const ::std::string& value); void set_name(const char* value); void set_name(const char* value, size_t size); ::std::string* mutable_name(); ::std::string* release_name(); void set_allocated_name(::std::string* name); // optional bytes data = 4; void clear_data(); static const int kDataFieldNumber = 4; const ::std::string& data() const; void set_data(const ::std::string& value); void set_data(const char* value); void set_data(const void* value, size_t size); ::std::string* mutable_data(); ::std::string* release_data(); void set_allocated_data(::std::string* data); // @@protoc_insertion_point(class_scope:IM.FileTrans) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; bool _is_default_instance_; ::google::protobuf::int64 req_id_; ::google::protobuf::int64 target_id_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr data_; mutable int _cached_size_; friend void protobuf_AddDesc_file_5ftrans_2eproto(); friend void protobuf_AssignDesc_file_5ftrans_2eproto(); friend void protobuf_ShutdownFile_file_5ftrans_2eproto(); void InitAsDefaultInstance(); static FileTrans* default_instance_; }; // =================================================================== // =================================================================== #if !PROTOBUF_INLINE_NOT_IN_HEADERS // FileTrans // optional int64 req_id = 1; inline void FileTrans::clear_req_id() { req_id_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 FileTrans::req_id() const { // @@protoc_insertion_point(field_get:IM.FileTrans.req_id) return req_id_; } inline void FileTrans::set_req_id(::google::protobuf::int64 value) { req_id_ = value; // @@protoc_insertion_point(field_set:IM.FileTrans.req_id) } // optional int64 target_id = 2; inline void FileTrans::clear_target_id() { target_id_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 FileTrans::target_id() const { // @@protoc_insertion_point(field_get:IM.FileTrans.target_id) return target_id_; } inline void FileTrans::set_target_id(::google::protobuf::int64 value) { target_id_ = value; // @@protoc_insertion_point(field_set:IM.FileTrans.target_id) } // optional string name = 3; inline void FileTrans::clear_name() { name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& FileTrans::name() const { // @@protoc_insertion_point(field_get:IM.FileTrans.name) return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void FileTrans::set_name(const ::std::string& value) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:IM.FileTrans.name) } inline void FileTrans::set_name(const char* value) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:IM.FileTrans.name) } inline void FileTrans::set_name(const char* value, size_t size) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:IM.FileTrans.name) } inline ::std::string* FileTrans::mutable_name() { // @@protoc_insertion_point(field_mutable:IM.FileTrans.name) return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* FileTrans::release_name() { return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void FileTrans::set_allocated_name(::std::string* name) { if (name != NULL) { } else { } name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:IM.FileTrans.name) } // optional bytes data = 4; inline void FileTrans::clear_data() { data_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& FileTrans::data() const { // @@protoc_insertion_point(field_get:IM.FileTrans.data) return data_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void FileTrans::set_data(const ::std::string& value) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:IM.FileTrans.data) } inline void FileTrans::set_data(const char* value) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:IM.FileTrans.data) } inline void FileTrans::set_data(const void* value, size_t size) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:IM.FileTrans.data) } inline ::std::string* FileTrans::mutable_data() { // @@protoc_insertion_point(field_mutable:IM.FileTrans.data) return data_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* FileTrans::release_data() { return data_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void FileTrans::set_allocated_data(::std::string* data) { if (data != NULL) { } else { } data_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), data); // @@protoc_insertion_point(field_set_allocated:IM.FileTrans.data) } #endif // !PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace IM // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_file_5ftrans_2eproto__INCLUDED
[ "dzshubin@live.com" ]
dzshubin@live.com
947dd8040df0df76aeff5c70cd9f6390bef2032a
4f8e66ebd1bc845ba011907c9fc7c6400dd7a6be
/SDL_Core/src/components/JSONHandler/src/RPC2ObjectsImpl/NsRPC2Communication/BasicCommunication/OnAppDeactivatedMarshaller.cpp
89a0d842356ea47d01c6a9ff2c296dd23faeed6d
[]
no_license
zhanzhengxiang/smartdevicelink
0145c304f28fdcebb67d36138a3a34249723ae28
fbf304e5c3b0b269cf37d3ab22ee14166e7a110b
refs/heads/master
2020-05-18T11:54:10.005784
2014-05-18T09:46:33
2014-05-18T09:46:33
20,008,961
1
0
null
null
null
null
UTF-8
C++
false
false
4,563
cpp
// // Copyright (c) 2013, Ford Motor Company // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following // disclaimer in the documentation and/or other materials provided with the // distribution. // // Neither the name of the Ford Motor Company nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include "../src/../include/JSONHandler/RPC2Objects/NsRPC2Communication/BasicCommunication/OnAppDeactivated.h" #include "../src/SDLRPCObjectsImpl/V2/DeactivateReasonMarshaller.h" #include "../src/SDLRPCObjectsImpl/V2/ResultMarshaller.h" #include "../src/../src/RPC2ObjectsImpl//NsRPC2Communication/BasicCommunication/OnAppDeactivatedMarshaller.h" /* interface NsRPC2Communication::BasicCommunication version 1.2 generated at Thu Jan 24 06:41:15 2013 source stamp Wed Jan 23 13:56:28 2013 author RC */ using namespace NsRPC2Communication::BasicCommunication; bool OnAppDeactivatedMarshaller::checkIntegrity(OnAppDeactivated& s) { return checkIntegrityConst(s); } bool OnAppDeactivatedMarshaller::fromString(const std::string& s,OnAppDeactivated& e) { try { Json::Reader reader; Json::Value json; if(!reader.parse(s,json,false)) return false; if(!fromJSON(json,e)) return false; } catch(...) { return false; } return true; } const std::string OnAppDeactivatedMarshaller::toString(const OnAppDeactivated& e) { Json::FastWriter writer; return checkIntegrityConst(e) ? writer.write(toJSON(e)) : ""; } bool OnAppDeactivatedMarshaller::checkIntegrityConst(const OnAppDeactivated& s) { if(s.appName.length()>100) return false; if(!NsSmartDeviceLinkRPCV2::DeactivateReasonMarshaller::checkIntegrityConst(s.reason)) return false; return true; } Json::Value OnAppDeactivatedMarshaller::toJSON(const OnAppDeactivated& e) { Json::Value json(Json::objectValue); if(!checkIntegrityConst(e)) return Json::Value(Json::nullValue); json["jsonrpc"]=Json::Value("2.0"); json["method"]=Json::Value("BasicCommunication.OnAppDeactivated"); json["params"]=Json::Value(Json::objectValue); json["params"]["appName"]=Json::Value(e.appName);; json["params"]["reason"]=NsSmartDeviceLinkRPCV2::DeactivateReasonMarshaller::toJSON(e.reason);; json["params"]["appId"]=Json::Value(e.appId);; return json; } bool OnAppDeactivatedMarshaller::fromJSON(const Json::Value& json,OnAppDeactivated& c) { try { if(!json.isObject()) return false; if(!json.isMember("jsonrpc") || !json["jsonrpc"].isString() || json["jsonrpc"].asString().compare("2.0")) return false; if(!json.isMember("method") || !json["method"].isString() || json["method"].asString().compare("BasicCommunication.OnAppDeactivated")) return false; if(!json.isMember("params")) return false; Json::Value js=json["params"]; if(!js.isObject()) return false; if(!js.isMember("appName") || !js["appName"].isString()) return false; c.appName=js["appName"].asString(); if(c.appName.length()>100) return false; if(!js.isMember("reason") || !NsSmartDeviceLinkRPCV2::DeactivateReasonMarshaller::fromJSON(js["reason"],c.reason)) return false; if(!js.isMember("appId") || !js["appId"].isInt()) return false; c.appId=js["appId"].asInt(); } catch(...) { return false; } return checkIntegrity(c); }
[ "kburdet1@ford.com" ]
kburdet1@ford.com
137fcd1570d972feecd2f6f47059cc226b108a7d
06df3293d43fd2dc5241ac9c89db2c39565193c3
/src/dronecontrol/src/VERSAO_28_SET.cpp
efda71c5a3a5968d90f5c300a761011a9576b91e
[]
no_license
JoseColombini/catkin_ws
10db102db1486b496742b863e389043f928bdf32
a73931eb8a7c5cc3e188d73a5745938feb8da46c
refs/heads/master
2020-08-02T23:49:03.412606
2019-11-29T21:25:04
2019-11-29T21:25:04
211,551,992
0
1
null
null
null
null
UTF-8
C++
false
false
12,174
cpp
#include <stdlib.h> #include "math.h" #include <ros/ros.h> #include <std_msgs/String.h> #include <std_msgs/Bool.h> #include <geometry_msgs/PoseStamped.h> #include <mavros_msgs/CommandBool.h> #include <mavros_msgs/SetMode.h> #include <mavros_msgs/State.h> #include <geometry_msgs/TwistStamped.h> #include <mavros_msgs/GlobalPositionTarget.h> #include <mavros_msgs/CommandHome.h> #include <sensor_msgs/NavSatFix.h> #include <fstream> #include <iostream> #define GPS_ERROR 0.000005 #define ERROR 0.5 #define ERROR_ALTITUDE 0.3 /* O pacote "mavros_msgS" contém todas as mensagens necessárias para o funcionamento dos "services" e dos "topics" oriundos do pacote MAVROS. Todos os serviços e tópicos, assim como seus respectivos tipos de mensagens, estão documentados na MAVROS wiki. */ float position_now[3]; mavros_msgs::State current_state; bool interrupt_message; bool node_message; bool aligned_message; geometry_msgs::TwistStamped twist; sensor_msgs::NavSatFix gps_pose; sensor_msgs::NavSatFix HOME_POSITION; sensor_msgs::NavSatFix SEARCH_POSITION; /****************** Search Position Setup ********************/ void state_cb(const mavros_msgs::State::ConstPtr& msg){ current_state = *msg; } /*Criamos uma simples função que salva o estado momentâneo do vôo. Ela nos permite checar parâmetros como: connection, arming e offboard flags. */ void callback_fcu_pose(const geometry_msgs::PoseStamped msg) { //printf ("Got data: %f, %f, %f \n", msg.pose.position.x, msg.pose.position.y, msg.pose.position.z ); position_now[0] = msg.pose.position.x; position_now[1] = msg.pose.position.y; position_now[2] = msg.pose.position.z; } void callback_fcu_interrompe(const std_msgs::Bool mensagem) { interrupt_message = mensagem.data; } void callback_fcu_node(const std_msgs::Bool mensagem) { node_message = mensagem.data; } void callback_fcu_aligned(const std_msgs::Bool mensagem) { aligned_message = mensagem.data; } // TESTAR GPS ERROR void go_to_global_pose(double latitude, double longitude, double change_height) { ros::NodeHandle nh; ros::Rate rate(20.0); ros::Publisher gps_pos_pub = nh.advertise<mavros_msgs::GlobalPositionTarget> ("mavros/setpoint_position/global", 10); mavros_msgs::GlobalPositionTarget g_pose; g_pose.latitude = latitude; g_pose.longitude = longitude; g_pose.altitude = gps_pose.altitude + change_height; //Mantenha a altitude atual, some change_height while (((gps_pose.latitude - g_pose.latitude) > GPS_ERROR) && ((gps_pose.longitude - g_pose.longitude) > GPS_ERROR)) { gps_pos_pub.publish(g_pose); rate.sleep(); } } // REFEITO void return_to_home(){ ros::NodeHandle nh; ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", 10); ros::Publisher vel_pos_pub = nh.advertise<geometry_msgs::TwistStamped> ("mavros/setpoint_velocity/cmd_vel", 10); ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool> ("mavros/cmd/arming"); ros::Rate rate(20.0); geometry_msgs::PoseStamped pose; geometry_msgs::TwistStamped twist; mavros_msgs::CommandBool arm_cmd; //printf("%f - %f", gps_pose.latitude, HOME_POSITION.latitude); while (abs(gps_pose.latitude - HOME_POSITION.latitude) > GPS_ERROR || abs(gps_pose.longitude - HOME_POSITION.longitude) > GPS_ERROR) { printf("Returning to home!"); go_to_global_pose(HOME_POSITION.latitude, HOME_POSITION.longitude, 0); } printf("%f", position_now[2]); while (position_now[2] > 0.3) { //printf("It's going down!"); twist.twist.linear.x = 0; twist.twist.linear.y = 0; twist.twist.linear.z = -1; vel_pos_pub.publish(twist); ros::spinOnce(); rate.sleep(); } //mavros_msgs::CommandBool arm_cmd; arm_cmd.request.value = false; arming_client.call(arm_cmd); printf("Mission executed successfully ;)"); for(int i=0; i < 333; i++) { printf("VOA SKYRATS "); arming_client.call(arm_cmd); } exit(0); } // ANALIZAR void delivery_package(){ ros::NodeHandle nh; ros::Publisher vel_pos_pub = nh.advertise<geometry_msgs::TwistStamped> ("mavros/setpoint_velocity/cmd_vel", 10); ros::Rate rate(20.0); //desce um pouco while(fabs(position_now[2] - 1.0) > ERROR_ALTITUDE){ printf("[ INFO ] Flying down to delivery the package."); twist.twist.linear.x = 0.0; twist.twist.linear.y = 0.0; twist.twist.linear.z = -1.0; vel_pos_pub.publish(twist); ros::spinOnce(); rate.sleep(); } //abre a garra printf("[ INFO ] Robotic Claw opening."); system("./abrir_garra.sh"); //sobe mais um pouco por segurança while(fabs(position_now[2] - 4.0) > ERROR_ALTITUDE){ printf("[ INFO ] Flying up to return to home."); twist.twist.linear.x = 0.0; twist.twist.linear.y = 0.0; twist.twist.linear.z = 1.0; vel_pos_pub.publish(twist); ros::spinOnce(); rate.sleep(); } //volta pra casa return_to_home(); } // PEGAR VERIFICATION DO COLOMBINI (OU NAO) void verification(){ ros::NodeHandle nh; if(interrupt_message == 1){ printf("\n [ WARN ] Mission interrupted. Returning to home."); return_to_home(); } while(node_message == 1){ printf("\n [ WARN ] Mission interrupted. Drone trying to align."); if(aligned_message == 1){ /** get gps location and save in file**/ return_to_home(); } } } void set_position(double goal_x, double goal_y, double goal_z){ ros::NodeHandle nh; ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", 10); ros::Rate rate(20.0); geometry_msgs::PoseStamped pose; printf("\n [ INFO ] Going to position (%f, %f,%f)", goal_x, goal_y, goal_z); while(position_now[0] != goal_x && position_now[1] != goal_y && position_now[2] != goal_z){ printf("\n [ INFO ] Local position: (%f, %f, %f)", position_now[0], position_now[1], position_now[2]); pose.pose.position.x = goal_x; pose.pose.position.y = goal_y; pose.pose.position.z = goal_z; local_pos_pub.publish(pose); verification(); ros::spinOnce(); rate.sleep(); if ( (fabs(position_now[0] - goal_x) < ERROR) && fabs(position_now[1] - goal_y) < ERROR && fabs(position_now[2] - goal_z) < ERROR_ALTITUDE) break; } } //<sensor_msgs/NavSatFix.h> void gps_callback(const sensor_msgs::NavSatFix msg){ gps_pose = msg; //ROS_INFO("GPS Position: (%f, %f)", gps_pose.latitude, gps_pose.longitude); } int main(int argc, char **argv) { double search_height = 4.0; double r = search_height*sin(51* 3.14159265358979323846/180); double step = 1.5*r; SEARCH_POSITION.latitude = 47.09654; SEARCH_POSITION.longitude = 27.847389; printf("\n [ INFO ] Starting IMAV 2019 Delivery Packages mission (Skyrats)"); printf("\n [ INFO ] Powered by Amigos da Poli, Politecnica-USP and CITI"); ros::init(argc, argv, "Madrid_Mission_Control"); ros::NodeHandle nh; ros::Subscriber gps_sub = nh.subscribe<sensor_msgs::NavSatFix> ("/mavros/global_position/global", 10, gps_callback); ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State> ("mavros/state", 10, state_cb); ros::Subscriber pega_pose = nh.subscribe<geometry_msgs::PoseStamped> ("mavros/local_position/pose", 10, callback_fcu_pose); ros::Subscriber interrompe = nh.subscribe<std_msgs::Bool> ("interrompe", 1, callback_fcu_interrompe); ros::Subscriber node = nh.subscribe<std_msgs::Bool> ("pack/node", 10, callback_fcu_node); ros::Subscriber aligned = nh.subscribe<std_msgs::Bool> ("pack/aligned", 10, callback_fcu_aligned); ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", 10); ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool> ("mavros/cmd/arming"); ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode> ("mavros/set_mode"); ros::ServiceClient set_home = nh.serviceClient<mavros_msgs::CommandHome> ("mavros/cmd/set_home"); /*Acima, instanciamos um "publisher" a fim de publicar a posição da aeronave, bem como "clients" apropriedades, de forma a dar o comando "arm".*/ //the setpoint publishing rate MUST be faster than 2Hz ros::Rate rate(20.0); /* A pilha de vôo do PX4 possui um intervalo de 500ms entre dois comandos offboard. Se esse intervalo for excedido, o programa de comando irá voltar para o último estado da aeronave antes de entrar no modo offboard! */ while(ros::ok() && !current_state.connected){ printf("\n [ INFO ] Waiting for connection"); ros::spinOnce(); rate.sleep(); } /* Antes de publicarmos algo, nós esperamos a conexão a ser estabelecida entre a MAVROS e o autopilot. Esse loop se encerrará quando a mensagem for recebida! */ geometry_msgs::PoseStamped pose; pose.pose.position.x = 0; pose.pose.position.y = 0; pose.pose.position.z = 0; //send a few setpoints before starting for(int i = 100; ros::ok() && i > 0; --i){ local_pos_pub.publish(pose); ros::spinOnce(); rate.sleep(); } /* Antes de entrarmos no modo offboard, você tem que ter iniciado os setpoints de transmissão. Caso contrário, a escolha do modo de vôo será rejeitada (próx. passo). Aqui, o número 100 foi uma escolha arbitrária */ mavros_msgs::SetMode offb_set_mode; offb_set_mode.request.custom_mode = "OFFBOARD"; node_message = 0; mavros_msgs::CommandBool arm_cmd; arm_cmd.request.value = true; ros::Time last_request = ros::Time::now(); pose.pose.position.x = 0.0; pose.pose.position.y = 0.0; pose.pose.position.z = search_height; local_pos_pub.publish(pose); while(ros::ok()){ if( current_state.mode != "OFFBOARD" && (ros::Time::now() - last_request > ros::Duration(5.0))){ if( set_mode_client.call(offb_set_mode) && offb_set_mode.response.mode_sent){ ROS_INFO("\n[ INFO ] Offboard enabled"); } last_request = ros::Time::now(); } else { if( !current_state.armed && (ros::Time::now() - last_request > ros::Duration(5.0))){ if( arming_client.call(arm_cmd) && arm_cmd.response.success){ ROS_INFO("\n[ WARN ] Skyrats MAV armed"); } last_request = ros::Time::now(); } } local_pos_pub.publish(pose); HOME_POSITION = gps_pose; //Condicional para checar se o drone decolou! if (fabs(position_now[2] - search_height) < ERROR){ //while () ROS_WARN("Skyrats MAV Takeoff!\n"); /*********** goas to search position and sets as home **********/ go_to_global_pose(SEARCH_POSITION.latitude, SEARCH_POSITION.longitude, 0); mavros_msgs::CommandHome NEW_HOME; NEW_HOME.request.latitude = gps_pose.latitude; NEW_HOME.request.longitude = gps_pose.longitude; NEW_HOME.request.altitude = HOME_POSITION.altitude; set_home.call(NEW_HOME); /****************************************/ double width = 2; double total_width = 10; //total width of search rectangle double total_height = 15; //set_position(i*width, (j+1)*total_height, search_height);5; //total height of search rectangle // for(double s = 0; (s <= 10); s += step) // set_position(s, 0.0, search_height); double j = 1.0; for (int i = 0; i < total_width/width; i++) { set_position(i*width, j*total_height, search_height); j=1.0; set_position(i*width, j*total_height, search_height); i++; set_position(i*width, j*total_height, search_height); j = 0; set_position(i*width, j*total_height, search_height); } // Returning to Home return_to_home(); } //fim do if verificador de takeoff ros::spinOnce(); rate.sleep(); } return 0; }
[ "gorinorr@gmail.com" ]
gorinorr@gmail.com
3dffb09ca0f26fc8610636a10674c910db0c24ec
d4a2c50a90792600c4d864fffe9c1a9d1ebd6acc
/mmlib/MMLib/FindView.cpp
f537086c122b6c3c24f6262e9be5290387761215
[]
no_license
iwasen/MyProg
3080316c3444e98d013587e92c066e278e796041
a0755a21d77647261df271ce301404a4e0294a7b
refs/heads/master
2022-12-30T00:28:07.539183
2020-10-25T06:36:27
2020-10-25T06:36:27
307,039,466
0
4
null
null
null
null
SHIFT_JIS
C++
false
false
6,727
cpp
// FindView.cpp : インプリメンテーション ファイル // #include "stdafx.h" #include "mmlib.h" #include "MMLibDoc.h" #include "FindDoc.h" #include "FindFrame.h" #include "FindView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CFindView IMPLEMENT_DYNCREATE(CFindView, CListView) CFindView::CFindView() { } CFindView::~CFindView() { } BEGIN_MESSAGE_MAP(CFindView, CListView) ON_WM_CREATE() ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnclick) ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemchanged) ON_WM_DESTROY() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFindView 描画 void CFindView::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: この位置に描画用のコードを追加してください } ///////////////////////////////////////////////////////////////////////////// // CFindView 診断 #ifdef _DEBUG void CFindView::AssertValid() const { CListView::AssertValid(); } void CFindView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CFindView メッセージ ハンドラ int CFindView::OnCreate(LPCREATESTRUCT lpCreateStruct) { lpCreateStruct->style |= LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS; if (CListView::OnCreate(lpCreateStruct) == -1) return -1; GetLixxxtrl().SetExtendedStyle(LVS_EX_FULLROWSELECT); GetLixxxtrl().SetImageList(&g_ImageList, LVSIL_SMALL); InsertColumns(); return 0; } void CFindView::InsertColumns() { struct LIxxxOLUMN { UINT text; int fmt; int width; } tColumn[] = { {IDS_NAME, LVCFMT_LEFT, 130}, {IDS_LIBRARY, LVCFMT_LEFT, 100}, {IDS_CREATOR, LVCFMT_LEFT, 100}, {IDS_REMARK, LVCFMT_LEFT, 100}, {IDS_KEYWORD, LVCFMT_LEFT, 100}, {IDS_CREATE_DATE, LVCFMT_LEFT, 110} }; int i; LV_COLUMN lvc; for (i = 0; i < sizeof(tColumn) / sizeof(LIxxxOLUMN); i++) { lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT; lvc.fmt = tColumn[i].fmt; lvc.pszText = (LPTSTR)(LPCTSTR)GetString(tColumn[i].text); lvc.cx = tColumn[i].width; GetLixxxtrl().InsertColumn(i, &lvc); } } void CFindView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (lHint == 1) { CFindDoc *pDoc = (CFindDoc *)GetDocument(); CString keywords, filter; keywords = pDoc->m_sKeyword; keywords.Replace(" ", " "); keywords.TrimLeft(); keywords.TrimRight(); if (!keywords.IsEmpty()) { filter = GetFilter(keywords, pDoc->m_nAndOr); if (!FindKeyword(filter)) AfxMessageBox(IDS_FIND_ERROR); } } } CString CFindView::GetFilter(CString &keywords, int nAndOr) { CString filter; CString keyword; while (!keywords.IsEmpty()) { keyword = keywords.SpanExcluding(" "); keywords = keywords.Mid(keyword.GetLength()); keywords.TrimLeft(); if (!filter.IsEmpty()) { if (nAndOr == 0) filter += "&"; else filter += "|"; } filter += "*SKEYWORD='" + keyword + "'"; } return filter; } BOOL CFindView::FindKeyword(LPCTSTR filter) { CPcserve pcserve; CPSDB db; CString dir, path; int nRead; KEYWORDBUF keywordBuf; KEYWORDREC keywordRec; CLixxxtrl &lc = GetLixxxtrl(); int nItem = 0; int nImage; CString str; CSelectItem *pSelectItem; int nRecSize; DeleteAllItems(); if (pcserve.Conxxxt(CHT_LOCAL, "", "MMLIB") != 0) return FALSE; ::GetKeywordDir(dir); path.Format("%s\\%s", dir, FN_KEYWORD_DBF); if (db.DBOpen(pcserve, path) != 0) { AfxMessageBox(IDS_NO_KEYWORD_INDEX); return TRUE; } if (db.DBRecSize(&nRecSize) != 0) return FALSE; if (nRecSize - 1 != sizeof(KEYWORDBUF)) { AfxMessageBox(IDS_OLD_KEYWORD_INDEX); return TRUE; } CWaitCursor wait; if (db.DBSetFilter(filter) != 0) return FALSE; while (db.DBReadNext(1, &keywordBuf, &nRead) == 0) { if (nRead == 0) break; db.DBGetFieldBuf(&keywordBuf, &keywordRec); pSelectItem = new CSelectItem; pSelectItem->m_sLibraryID = keywordRec.libraryID; if (keywordRec.idType == FIND_TYPE_FOLDER) { pSelectItem->m_sFolderID = keywordRec.id; if (keywordRec.folderType == FTYPE_GFOLDER) nImage = IMAGE_GFOLDER; else nImage = IMAGE_DFOLDER; } else { pSelectItem->m_sDataID = keywordRec.id; nImage = IMAGE_DATA; } lc.InsertItem(nItem, keywordRec.title, nImage); lc.SetItemText(nItem, 1, keywordRec.libraryName); lc.SetItemText(nItem, 2, keywordRec.creator); lc.SetItemText(nItem, 3, keywordRec.remark); lc.SetItemText(nItem, 4, keywordRec.keyword); FormatDate(keywordRec.createDate, str); lc.SetItemText(nItem, 5, str); lc.SetItemData(nItem, (DWORD_PTR)pSelectItem); nItem++; } str.Format(IDS_FIND_RESULT, nItem); GetParent()->SetWindowText(str); m_nSortItem = 0; m_nSortDir = 1; lc.SortItems(CompareItems, (LPARAM)this); return TRUE; } void CFindView::DeleteAllItems() { CLixxxtrl &lc = GetLixxxtrl(); int nItem = lc.GetItemCount(); for (int i = 0; i < nItem; i++) delete (CSelectItem *)lc.GetItemData(i); lc.DeleteAllItems(); } void CFindView::OnColumnclick(NMHDR* pNMHDR, LRESULT* pResult) { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; if (m_nSortItem != pNMListView->iSubItem) m_nSortDir = 1; else m_nSortDir *= -1; m_nSortItem = pNMListView->iSubItem; GetLixxxtrl().SortItems(CompareItems, (LPARAM)this); *pResult = 0; } int CALLBACK CFindView::CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { CFindView *pView = (CFindView *)lParamSort; CLixxxtrl &lc = pView->GetLixxxtrl(); LV_FINDINFO findInfo; int index1, index2; findInfo.flags = LVFI_PARAM; findInfo.lParam = lParam1; index1 = lc.FindItem(&findInfo); findInfo.flags = LVFI_PARAM; findInfo.lParam = lParam2; index2 = lc.FindItem(&findInfo); return lc.GetItemText(index1, pView->m_nSortItem).CompareNoCase(lc.GetItemText(index2, pView->m_nSortItem)) * pView->m_nSortDir; } void CFindView::OnItemchanged(NMHDR* pNMHDR, LRESULT* pResult) { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; if (pNMListView->uNewState & LVIS_SELECTED) { CLixxxtrl &lc = GetLixxxtrl(); CFindDoc *pFindDoc = (CFindDoc *)GetDocument(); pFindDoc->m_pMMLibDoc->UpdateAllViews(NULL, VIEWHINT_SELECTDATA, (CSelectItem *)lc.GetItemData(pNMListView->iItem)); } *pResult = 0; } void CFindView::OnDestroy() { DeleteAllItems(); CListView::OnDestroy(); }
[ "git@iwasen.jp" ]
git@iwasen.jp
cdbff612f04e490f690e5caff430b6995d9be8b9
d327e106285776f28ef1d6c8a7f561b7f05763a6
/SDL/RPGGame2/StateParser.h
405f75d5b4e43d0ae3f9cf62a5129426b561f342
[]
no_license
sky94520/old-code
a4bb7b6826906ffa02f57151af2dc21471cf2106
6b37cc7a9338d283a330b4afae2c7fbd8aa63683
refs/heads/master
2020-05-03T12:37:48.443045
2019-07-23T00:38:16
2019-07-23T00:38:16
178,631,201
0
0
null
null
null
null
UTF-8
C++
false
false
551
h
#pragma once #include<iostream> #include<vector> #include "tinyxml.h" #include "LoaderParams.h" #include "GameObjectFactory.h" #include "TextureManager.h" #include "GameObject.h" //class GameObject; class StateParser { private: void parseObjects(TiXmlElement*pStateRoot,std::vector<GameObject*> *pObjects); void parseTextures(TiXmlElement*pStateRoot,std::vector<std::string> *pTextureIDs); public: bool parseState(const char*stateFile,std::string stateID,std::vector<GameObject*>*pObjects,std::vector<std::string>*pTextureIDs); };
[ "541052067@qq.com" ]
541052067@qq.com
b0a28ffd826f46bac2330feda256a5af8666bfa4
55ebdde4755ef69c365c21d9cd5d46c3e5bda7de
/Shooter.h
1c891e9598405bf3dc25cc46f7a5f08ebbff9fa6
[]
no_license
niuguangxue/toys
9aa1ebb9cabe6e0a4f65be8b18dfd9e8edf13b08
639cb6e3d0d9cdaccbaf98b441f88a093f52a7c2
refs/heads/master
2022-04-04T21:34:24.680016
2019-12-29T13:56:20
2019-12-29T13:56:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
166
h
#pragma once #include "IDrawable.h" #include "IMouseAction.h" class CShooter: public IDrawable, public IMouseAction { public: CShooter(); virtual ~CShooter(); };
[ "niu91@qq.com" ]
niu91@qq.com
a0cb9a60c865a0907bdfb5e00266e2403ab8c72f
a2ac955d67fc1382bfb64f54059cdefe165928f4
/code/mathematics/primitive_root.cpp
067b139212da940b80e510b2b62bdbc2e762b782
[ "MIT" ]
permissive
sahedsohel/CompetitiveProgramming
4e12b5d2d3933598590278c8077bc2f2201b449d
5e05e8ae40a065b0f3baae85bc6b10414ada0c67
refs/heads/master
2020-07-16T19:49:40.424939
2016-08-05T13:59:42
2016-08-05T13:59:42
73,941,688
1
0
null
2016-11-16T17:00:33
2016-11-16T17:00:32
null
UTF-8
C++
false
false
390
cpp
#include "mod_pow.cpp" ll primitive_root(ll m) { vector<ll> div; for (ll i = 1; i*i <= m-1; i++) { if ((m-1) % i == 0) { if (i < m) div.push_back(i); if (m/i < m) div.push_back(m/i); } } rep(x,2,m) { bool ok = true; iter(it,div) if (mod_pow<ll>(x, *it, m) == 1) { ok = false; break; } if (ok) return x; } return -1; }
[ "suprdewd@gmail.com" ]
suprdewd@gmail.com
b67d4dbba86ff56ffbab2064e2e195b9bdb17d6a
234f4e8bb5ed49526aed2b9f0c18de135056c310
/NeatEngine/DefaultCamera.h
d71d95989e8cd2a009e02289c321b0b6f145f682
[]
no_license
peersmg/NeatEngine
b2ded034a7c7d746917a2e0a2f95bdd5d2ebf04a
1b86d587cfdbc673a6b3df02c95c21b71443219f
refs/heads/master
2020-05-21T20:28:06.841540
2017-04-29T20:45:50
2017-04-29T20:45:50
64,606,851
1
0
null
null
null
null
UTF-8
C++
false
false
161
h
#pragma once #include "GameObject.h" class CCamera; class Window; class DefaultCamera : public GameObject { public: DefaultCamera(); ~DefaultCamera(); };
[ "peersmg@gmail.com" ]
peersmg@gmail.com
b7f79931100fd3892b547a4a870b16d25d5539c6
4e7f71fa1a458c68629ba8c134931835594b8174
/Scene.h
989288b8375529b562f6d7cf6d0dc8b5c7a5e869
[ "Apache-2.0" ]
permissive
mahaupt/SimpleRay
a4388f942f80b4dea1512c7d5b59e48b26b93d82
c617ead954cf9d6c638554d404125c853120bac8
refs/heads/master
2023-04-04T11:07:10.806180
2021-04-09T17:09:45
2021-04-09T17:09:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,310
h
// Copyright 2016 Marcel Haupt // // 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. #pragma once #include <vector> #include "Vector3.h" #include "GameObject.h" #include "LightSource.h" #include "Camera.h" #include "Sphere.h" class Scene { private: static Scene* instance; std::vector<GameObject*> gameObjects; std::vector<LightSource*> lightSources; public: Scene(); ~Scene(); Sphere & createSphere(double radius, Vector3 position); Camera & createCamera(Vector3 position); void createLightSource(LightSource * lightsource); //sets and gets std::vector<GameObject*>* getGameObjects() { return &gameObjects; } std::vector<LightSource*>* getLightSources() { return &lightSources; } static Scene* getInstance() { return instance; } };
[ "subcortexx@gmail.com" ]
subcortexx@gmail.com
ca27e3660e2b58617b7c361452a9a7afb14a428f
dc34bcf7232e79324eb865ef0018c0f9acd44c53
/programming/hash-table/146.lru缓存机制.cpp
ba0234923c35787eae917c976f0122b69fd10a15
[]
no_license
yqtaowhu/DataStructureAndAlgorithm
a36173387e4c9b233f9095b7adbe492500a4c2ab
b7fbda40dd30d7e66dd3469d92be59988fe72783
refs/heads/master
2021-06-09T07:47:34.496426
2021-05-24T13:11:32
2021-05-24T13:11:32
63,948,564
26
35
null
null
null
null
UTF-8
C++
false
false
2,039
cpp
/* * @lc app=leetcode.cn id=146 lang=cpp * * [146] LRU缓存机制 */ // @lc code=start // https://leetcode-cn.com/problems/lru-cache/solution/lru-ce-lue-xiang-jie-he-shi-xian-by-labuladong/ class LRUCache { private: int cap; // 双链表:装着 (key, value) 元组 list<pair<int, int>> cache; // 哈希表:key 映射到 (key, value) 在 cache 中的位置 unordered_map<int, list<pair<int, int>>::iterator> map; public: LRUCache(int capacity) { this->cap = capacity; } int get(int key) { auto it = map.find(key); // 访问的 key 不存在 if (it == map.end()) return -1; // key 存在,把 (k, v) 换到队头 pair<int, int> kv = *map[key]; cache.erase(map[key]); cache.push_front(kv); // 更新 (key, value) 在 cache 中的位置 map[key] = cache.begin(); return kv.second; // value } void put(int key, int value) { /* 要先判断 key 是否已经存在 */ auto it = map.find(key); if (it == map.end()) { /* key 不存在,判断 cache 是否已满 */ if (cache.size() == cap) { // cache 已满,删除尾部的键值对腾位置 // cache 和 map 中的数据都要删除 auto lastPair = cache.back(); int lastKey = lastPair.first; map.erase(lastKey); cache.pop_back(); } // cache 没满,可以直接添加 cache.push_front(make_pair(key, value)); map[key] = cache.begin(); } else { /* key 存在,更改 value 并换到队头 */ cache.erase(map[key]); cache.push_front(make_pair(key, value)); map[key] = cache.begin(); } } }; /** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */ // @lc code=end
[ "yqtao@whu.edu.cn" ]
yqtao@whu.edu.cn
6ca8ed9e16ba68306f856f61a24545efc9559b38
1a747b63129a60390005837279778d821cf3837d
/Memory/AutoPtrTest.cpp
39d56496059def75bbf8f919a5185ab1954924d3
[]
no_license
zgglj2/PocoStudy
53b3b2bd40b12da7f3f71bbd729022fdc168e882
05b9fc08e4a3fb0dc0a1069aa66f71d1ad4bacbb
refs/heads/master
2021-06-24T07:37:09.188997
2020-12-26T14:44:28
2020-12-26T14:44:28
84,742,840
2
0
null
null
null
null
UTF-8
C++
false
false
731
cpp
#include <iostream> #include "Poco/AutoPtr.h" class RC0 { public: RC0() : _rc(1) { std::cout << __FUNCTION__ << " : Count=" << _rc << std::endl; } void duplicate() { ++_rc; std::cout << __FUNCTION__ << " : Count:" << _rc << std::endl; } void release() { --_rc; std::cout << __FUNCTION__ << " : Count:" << _rc << std::endl; if (_rc == 0) { delete this; } } private: int _rc; }; int main(int argc, char **argv) { RC0 *pNew = new RC0; Poco::AutoPtr<RC0> p1(pNew); Poco::AutoPtr<RC0> p2(p1); Poco::AutoPtr<RC0> p3(pNew, true); p2 = 0; p3 = 0; RC0 *pRC0 = p1; p1 = 0; p1 = new RC0; return 0; }
[ "7909213@qq.com" ]
7909213@qq.com
10aa2cabc1ba6e452fee9c18708dbbef413b9c86
1ae598933a5636746552f6db2a306f41f10b00f7
/src/crc32.cpp
f0d39223cf7053ada31d7adcdbbcd56ac0bb0d7c
[]
no_license
libretro/uae4arm-libretro
37beaf95bf25fe249ae8c04f1c0780576f663d4c
5cbf44464507ff9262c2403c9f8d5bc5957afd1a
refs/heads/master
2022-06-26T00:42:36.990108
2022-06-18T16:41:42
2022-06-18T16:41:42
66,605,446
7
14
null
2022-04-12T08:26:51
2016-08-26T01:18:01
C++
UTF-8
C++
false
false
9,427
cpp
#include "sysconfig.h" #include "sysdeps.h" #include "crc32.h" static unsigned long crc_table32[256]; static unsigned short crc_table16[256]; static void make_crc_table (void) { unsigned long c; unsigned short w; int n, k; for (n = 0; n < 256; n++) { c = (unsigned long)n; w = n << 8; for (k = 0; k < 8; k++) { c = (c >> 1) ^ (c & 1 ? 0xedb88320 : 0); w = (w << 1) ^ ((w & 0x8000) ? 0x1021 : 0); } crc_table32[n] = c; crc_table16[n] = w; } } uae_u32 get_crc32_val (uae_u8 v, uae_u32 crc) { if (!crc_table32[1]) make_crc_table(); crc ^= 0xffffffff; crc = crc_table32[(crc ^ v) & 0xff] ^ (crc >> 8); return crc ^ 0xffffffff; } uae_u32 get_crc32 (uae_u8 *buf, int len) { uae_u32 crc; if (!crc_table32[1]) make_crc_table(); crc = 0xffffffff; while (len-- > 0) crc = crc_table32[(crc ^ (*buf++)) & 0xff] ^ (crc >> 8); return crc ^ 0xffffffff; } uae_u16 get_crc16( uae_u8 *buf, int len) { uae_u16 crc; if (!crc_table32[1]) make_crc_table(); crc = 0xffff; while (len-- > 0) crc = (crc << 8) ^ crc_table16[((crc >> 8) ^ (*buf++)) & 0xff]; return crc; } #ifndef GET_UINT32_BE #define GET_UINT32_BE(n,b,i) \ { \ (n) = ( (unsigned long) (b)[(i) ] << 24 ) \ | ( (unsigned long) (b)[(i) + 1] << 16 ) \ | ( (unsigned long) (b)[(i) + 2] << 8 ) \ | ( (unsigned long) (b)[(i) + 3] ); \ } #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n,b,i) \ { \ (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 3] = (unsigned char) ( (n) ); \ } #endif typedef struct { unsigned long total[2]; /*!< number of bytes processed */ unsigned long state[5]; /*!< intermediate digest state */ unsigned char buffer[64]; /*!< data block being processed */ } sha1_context; static void sha1_starts( sha1_context *ctx ) { ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; ctx->state[4] = 0xC3D2E1F0; } static void sha1_process( sha1_context *ctx, unsigned char data[64] ) { unsigned long temp, W[16], A, B, C, D, E; GET_UINT32_BE( W[0], data, 0 ); GET_UINT32_BE( W[1], data, 4 ); GET_UINT32_BE( W[2], data, 8 ); GET_UINT32_BE( W[3], data, 12 ); GET_UINT32_BE( W[4], data, 16 ); GET_UINT32_BE( W[5], data, 20 ); GET_UINT32_BE( W[6], data, 24 ); GET_UINT32_BE( W[7], data, 28 ); GET_UINT32_BE( W[8], data, 32 ); GET_UINT32_BE( W[9], data, 36 ); GET_UINT32_BE( W[10], data, 40 ); GET_UINT32_BE( W[11], data, 44 ); GET_UINT32_BE( W[12], data, 48 ); GET_UINT32_BE( W[13], data, 52 ); GET_UINT32_BE( W[14], data, 56 ); GET_UINT32_BE( W[15], data, 60 ); #define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) #define R(t) \ ( \ temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ \ W[(t - 14) & 0x0F] ^ W[ t & 0x0F], \ ( W[t & 0x0F] = S(temp,1) ) \ ) #define P(a,b,c,d,e,x) \ { \ e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \ } A = ctx->state[0]; B = ctx->state[1]; C = ctx->state[2]; D = ctx->state[3]; E = ctx->state[4]; #define F(x,y,z) (z ^ (x & (y ^ z))) #define K 0x5A827999 P( A, B, C, D, E, W[0] ); P( E, A, B, C, D, W[1] ); P( D, E, A, B, C, W[2] ); P( C, D, E, A, B, W[3] ); P( B, C, D, E, A, W[4] ); P( A, B, C, D, E, W[5] ); P( E, A, B, C, D, W[6] ); P( D, E, A, B, C, W[7] ); P( C, D, E, A, B, W[8] ); P( B, C, D, E, A, W[9] ); P( A, B, C, D, E, W[10] ); P( E, A, B, C, D, W[11] ); P( D, E, A, B, C, W[12] ); P( C, D, E, A, B, W[13] ); P( B, C, D, E, A, W[14] ); P( A, B, C, D, E, W[15] ); P( E, A, B, C, D, R(16) ); P( D, E, A, B, C, R(17) ); P( C, D, E, A, B, R(18) ); P( B, C, D, E, A, R(19) ); #undef K #undef F #define F(x,y,z) (x ^ y ^ z) #define K 0x6ED9EBA1 P( A, B, C, D, E, R(20) ); P( E, A, B, C, D, R(21) ); P( D, E, A, B, C, R(22) ); P( C, D, E, A, B, R(23) ); P( B, C, D, E, A, R(24) ); P( A, B, C, D, E, R(25) ); P( E, A, B, C, D, R(26) ); P( D, E, A, B, C, R(27) ); P( C, D, E, A, B, R(28) ); P( B, C, D, E, A, R(29) ); P( A, B, C, D, E, R(30) ); P( E, A, B, C, D, R(31) ); P( D, E, A, B, C, R(32) ); P( C, D, E, A, B, R(33) ); P( B, C, D, E, A, R(34) ); P( A, B, C, D, E, R(35) ); P( E, A, B, C, D, R(36) ); P( D, E, A, B, C, R(37) ); P( C, D, E, A, B, R(38) ); P( B, C, D, E, A, R(39) ); #undef K #undef F #define F(x,y,z) ((x & y) | (z & (x | y))) #define K 0x8F1BBCDC P( A, B, C, D, E, R(40) ); P( E, A, B, C, D, R(41) ); P( D, E, A, B, C, R(42) ); P( C, D, E, A, B, R(43) ); P( B, C, D, E, A, R(44) ); P( A, B, C, D, E, R(45) ); P( E, A, B, C, D, R(46) ); P( D, E, A, B, C, R(47) ); P( C, D, E, A, B, R(48) ); P( B, C, D, E, A, R(49) ); P( A, B, C, D, E, R(50) ); P( E, A, B, C, D, R(51) ); P( D, E, A, B, C, R(52) ); P( C, D, E, A, B, R(53) ); P( B, C, D, E, A, R(54) ); P( A, B, C, D, E, R(55) ); P( E, A, B, C, D, R(56) ); P( D, E, A, B, C, R(57) ); P( C, D, E, A, B, R(58) ); P( B, C, D, E, A, R(59) ); #undef K #undef F #define F(x,y,z) (x ^ y ^ z) #define K 0xCA62C1D6 P( A, B, C, D, E, R(60) ); P( E, A, B, C, D, R(61) ); P( D, E, A, B, C, R(62) ); P( C, D, E, A, B, R(63) ); P( B, C, D, E, A, R(64) ); P( A, B, C, D, E, R(65) ); P( E, A, B, C, D, R(66) ); P( D, E, A, B, C, R(67) ); P( C, D, E, A, B, R(68) ); P( B, C, D, E, A, R(69) ); P( A, B, C, D, E, R(70) ); P( E, A, B, C, D, R(71) ); P( D, E, A, B, C, R(72) ); P( C, D, E, A, B, R(73) ); P( B, C, D, E, A, R(74) ); P( A, B, C, D, E, R(75) ); P( E, A, B, C, D, R(76) ); P( D, E, A, B, C, R(77) ); P( C, D, E, A, B, R(78) ); P( B, C, D, E, A, R(79) ); #undef K #undef F ctx->state[0] += A; ctx->state[1] += B; ctx->state[2] += C; ctx->state[3] += D; ctx->state[4] += E; } /* * SHA-1 process buffer */ static void sha1_update( sha1_context *ctx, unsigned char *input, int ilen ) { int fill; unsigned long left; if( ilen <= 0 ) return; left = ctx->total[0] & 0x3F; fill = 64 - left; ctx->total[0] += ilen; ctx->total[0] &= 0xFFFFFFFF; if( ctx->total[0] < (unsigned long) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), (void *) input, fill ); sha1_process( ctx, ctx->buffer ); input += fill; ilen -= fill; left = 0; } while( ilen >= 64 ) { sha1_process( ctx, input ); input += 64; ilen -= 64; } if( ilen > 0 ) { memcpy( (void *) (ctx->buffer + left), (void *) input, ilen ); } } static const unsigned char sha1_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* * SHA-1 final digest */ static void sha1_finish( sha1_context *ctx, unsigned char output[20] ) { unsigned long last, padn; unsigned long high, low; unsigned char msglen[8]; high = ( ctx->total[0] >> 29 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); PUT_UINT32_BE( high, msglen, 0 ); PUT_UINT32_BE( low, msglen, 4 ); last = ctx->total[0] & 0x3F; padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); sha1_update( ctx, (unsigned char *) sha1_padding, padn ); sha1_update( ctx, msglen, 8 ); PUT_UINT32_BE( ctx->state[0], output, 0 ); PUT_UINT32_BE( ctx->state[1], output, 4 ); PUT_UINT32_BE( ctx->state[2], output, 8 ); PUT_UINT32_BE( ctx->state[3], output, 12 ); PUT_UINT32_BE( ctx->state[4], output, 16 ); } void get_sha1(uae_u8 *input, int len, uae_u8 *out) { sha1_context ctx; sha1_starts( &ctx ); sha1_update( &ctx, input, len ); sha1_finish( &ctx, out ); } char *get_sha1_txt(uae_u8 *input, int len) { static char outtxt[SHA1_SIZE * 2 + 1]; uae_u8 out[SHA1_SIZE]; int i; char *p; p = outtxt; get_sha1(input, len, out); for (i = 0; i < SHA1_SIZE; i++) { sprintf(p, "%02X", out[i]); p += 2; } *p = 0; return outtxt; }
[ "darcelf@gmail.com" ]
darcelf@gmail.com
f8a04d9ee63753af82ed201f707ba3a920989f17
6ad53ab7d4fda7b64e0f40ad0965ba08af1a8f56
/Hub08_LedMatrix/Hub08_LedMatrix.ino
ce966234cda65ffdd51446e116da94c23d1b5649
[]
no_license
parker123123/Arduino-projects
9f13754a7e2befa25361ce5390eb3865c70b533d
84444a6ec8088f426a6104123679f214e58b0358
refs/heads/master
2023-07-02T05:42:47.254393
2020-07-19T11:01:21
2020-07-19T11:01:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,632
ino
/** * LED Matrix library for http://www.seeedstudio.com/depot/ultrathin-16x32-red-led-matrix-panel-p-1582.html * The LED Matrix panel has 32x16 pixels. Several panel can be combined together as a large screen. * * Coordinate & Connection (Arduino -> panel 0 -> panel 1 -> ...) * (0, 0) (0, 0) * +--------+--------+--------+ +--------+--------+ * | 5 | 4 | 3 | | 1 | 0 | * | | | | | | |<----- Arduino * +--------+--------+--------+ +--------+--------+ * | 2 | 1 | 0 | (64, 16) * | | | |<----- Arduino * +--------+--------+--------+ * (96, 32) * */ #define FONT8x8 0 #include <avr/pgmspace.h> #include "LEDMatrix.h" #include "font.h" #define WIDTH 64*1 // 2 panels * 64 #define HEIGHT 16 #if USE_SPI #include <SPI.h> // Arduino IDE compilation won't work without this #endif // hub08 pinout: la lb lc ld en r1 lat clk // LEDMatrix(a, b, c, d, oe, r1, stb, clk); LEDMatrix matrix(4, 5, 6, 7, 9, 11, 10, 13); // Display Buffer 128 = 64 * 16 / 8 uint8_t displaybuf[(WIDTH/8) * HEIGHT*2]; uint8_t displaybuf_w[((WIDTH/8)+1) * HEIGHT]; byte cell[16]; void MatrixWriteCharacter(int x,int y, char character) { //Serial.print(x); //Serial.print(" "); //Serial.println(character); #if FONT8x8 for(int i=0; i<8; i++) { uint8_t *pDst = displaybuf_w + (i+y) * ((WIDTH / 8) + 1) + x ; *pDst = (font_8x8[character - 0x20][i]); } #else for(int i=0; i<16; i++) { cell[i] = pgm_read_byte_near(&font_8x16[(character - 0x20)][i]); } //uint8_t *pDst = displaybuf_w + (y) * ((WIDTH / 8) + 1) + x ; uint8_t *pDst = displaybuf_w + x + y * ((WIDTH/8)+1); byte mask = 1; for(int j=0; j<8; j++) { byte out = 0; for(int i=0; i<8; i++) { out <<= 1; if ( cell[i] & mask ) { out |= 1; } } *pDst = out; pDst += (WIDTH/8)+1; mask <<= 1; } mask = 1; for(int j=0; j<8; j++) { byte out = 0; for(int i=8; i<16; i++) { out <<= 1; if ( cell[i] & mask ) { out |= 1; } } *pDst = out; pDst += (WIDTH/8)+1; mask <<= 1; } #endif } void matrixPrint(String c) { //c="33"; //Serial.println(c); //Serial.println(c.length()); for (int i=0 ; i<c.length() ; i++) { MatrixWriteCharacter(i,3,c[i]); matrix.scan(); //Serial.print(i); //Serial.print(" -> "); //Serial.println(c[i]); } } void setup() { matrix.begin(displaybuf, WIDTH, HEIGHT); Serial.begin(115200); matrix.clear(); //matrixPrint("12345678"); // uint8_t *pDst = displaybuf + y * (WIDTH / 8) + x / 8; memset(displaybuf_w, 0, sizeof(displaybuf_w)); } void matrixDelay(int x) { for (int y=0; y<x; y++) { matrix.scan(); } } //String poruka="X XX XOX XOOX XOoOX XOooOX XOoIoOX XOoiioOX "; //String poruka=" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras blandit libero id ex dapibus suscipit. Proin vitae cursus eros. Ut porttitor congue metus at viverra. In consectetur ex massa."; String poruka="!\"#$%&'()*+,-./0123456789:;<=>?@AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqReSsTtUuVvWwXxYyZz[\\]^_`{|}~"; //String poruka="~"; int pos = 0; // position in circular display void loop() { for (int p=0; p<poruka.length() ; p++) { pos = ( pos + 1 ) % (( WIDTH / 8 )+1); // int pos_ch = ( pos + (WIDTH/8) ) % (( WIDTH / 8 )+1); int pos_ch = ( pos + (WIDTH/8) ) % (( WIDTH / 8 )+1); MatrixWriteCharacter(pos_ch,0,poruka.charAt(p)); int step_up = ((WIDTH/8)+1)-pos; // move up one line when falling off the end of circular buffer Serial.print(pos); Serial.print(" step_up="); Serial.print(step_up); Serial.print(" char="); Serial.println(poruka.charAt(p)); for (int o=0; o<8; o++) { uint8_t *src = displaybuf_w + pos; uint8_t *dest = matrix.offscreen_buffer(); int i = 0; for (int y = 0; y < HEIGHT; y++ ) { for (int x = 0; x < (WIDTH/8); x++) { int j = ( x < step_up ? y : y-1 ) * ((WIDTH/8)+1) + x; int j1 = ( x+1 < step_up ? y : y-1 ) * ((WIDTH/8)+1) + x+1; *(dest + i) = ( *(src + j) << o ) | (( *(src + j1) & ( 0xff << 8 - o ) ) >> 8 - o ); // *(dest + i) = *(src + j); #if USE_SPI matrix.scan(); delayMicroseconds(100 / (WIDTH / 64)); #else matrix.scan(); delayMicroseconds(100 / (WIDTH / 64)); #endif i++; } } matrix.swap(); } } }
[ "dpavlin@rot13.org" ]
dpavlin@rot13.org
6358f63933333b5f476aacd9572dd814fcb2bb68
e6fcdcf4f7e85a7ab3e2f83dde44df34f7e1cbd5
/src/inet/tls/tlsclient.hpp
6bcc7f7200099607aab2c1534adbe41e3632812a
[]
no_license
rubenmrk/network
57df1256dfd274e92e0aae90159f217c8bdc2247
c2f82208c48b053bc86e636a483b18f86de75a50
refs/heads/master
2020-05-16T11:00:47.595740
2019-04-23T11:45:20
2019-04-23T11:45:20
183,002,012
0
0
null
null
null
null
UTF-8
C++
false
false
1,672
hpp
#pragma once #include "../tcp/tcpclient.hpp" #include <openssl/ssl.h> // If for some inane reason you don't want to use exception handling or want to use standard library exceptions //#define INET_TLS_DISABLE_CUSTOM_EXCEPTION namespace inet::tls { enum class except_e { PRNG, TLS_VER, CIPHER, CERT_LOAD, CONNECT, SSL_STRUCT, SET_HOSTNAME, SSL_SOCK, HANDSHAKE, VERIFY, WRITE, READ }; #ifndef INET_TLS_DISABLE_CUSTOM_EXCEPTION class exception : public std::exception { public: exception(except_e ecode); const char * what() const noexcept override; const char * details() noexcept; const except_e ecode; }; #endif class streambuf : public tcp::streambuf { public: streambuf(SSL *ssl); streambuf(); protected: void readfunc(const void * const t, size_t& res, char *begin, size_t len) override; void writefunc(const void * const t, size_t& res, char *begin, size_t len) override; }; class client : public tcp::client { public: client(); ~client(); bool is_open() const noexcept override; void open(std::string_view node, std::string_view service) override; void open(std::string_view node, std::string_view service, const uint8_t *protocolList, unsigned int listSize); void close() override; const char * getprotocol() override; private: void _createsb() override; void _resetsb() override; void _connect(std::string_view node, std::string_view service, const uint8_t *protocolList, unsigned int listSize); void _disconnect(); SSL* _ssl; }; }
[ "paradoxnl@openmailbox.org" ]
paradoxnl@openmailbox.org
454d10aea09bd5598bcd94c40fea896067942f69
4ccf73a7282b56a47b9211e6b759a3d1c0d95463
/src/objects/fixed-array.h
7bb7b79e0411a3413e71a1423a1a6db5754a1e6b
[ "BSD-3-Clause", "Apache-2.0", "SunPro" ]
permissive
RekGRpth/v8
a83c039904e042d447f6c787a3698482d02987c3
eec34b405e7718657d0ecc2058a8945bf3a5af01
refs/heads/master
2023-08-21T14:00:15.598843
2020-09-17T03:09:31
2020-09-17T04:08:12
296,223,125
1
0
NOASSERTION
2023-07-20T10:26:53
2020-09-17T04:55:50
null
UTF-8
C++
false
false
22,361
h
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_FIXED_ARRAY_H_ #define V8_OBJECTS_FIXED_ARRAY_H_ #include "src/handles/maybe-handles.h" #include "src/objects/instance-type.h" #include "src/objects/objects.h" #include "src/objects/smi.h" #include "torque-generated/class-definitions-tq.h" // Has to be the last include (doesn't have include guards): #include "src/objects/object-macros.h" namespace v8 { namespace internal { #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \ V(BYTECODE_ARRAY_CONSTANT_POOL_SUB_TYPE) \ V(BYTECODE_ARRAY_HANDLER_TABLE_SUB_TYPE) \ V(CODE_STUBS_TABLE_SUB_TYPE) \ V(COMPILATION_CACHE_TABLE_SUB_TYPE) \ V(CONTEXT_SUB_TYPE) \ V(COPY_ON_WRITE_SUB_TYPE) \ V(DEOPTIMIZATION_DATA_SUB_TYPE) \ V(DESCRIPTOR_ARRAY_SUB_TYPE) \ V(EMBEDDED_OBJECT_SUB_TYPE) \ V(ENUM_CACHE_SUB_TYPE) \ V(ENUM_INDICES_CACHE_SUB_TYPE) \ V(DEPENDENT_CODE_SUB_TYPE) \ V(DICTIONARY_ELEMENTS_SUB_TYPE) \ V(DICTIONARY_PROPERTIES_SUB_TYPE) \ V(EMPTY_PROPERTIES_DICTIONARY_SUB_TYPE) \ V(PACKED_ELEMENTS_SUB_TYPE) \ V(FAST_PROPERTIES_SUB_TYPE) \ V(FAST_TEMPLATE_INSTANTIATIONS_CACHE_SUB_TYPE) \ V(HANDLER_TABLE_SUB_TYPE) \ V(JS_COLLECTION_SUB_TYPE) \ V(JS_WEAK_COLLECTION_SUB_TYPE) \ V(NOSCRIPT_SHARED_FUNCTION_INFOS_SUB_TYPE) \ V(NUMBER_STRING_CACHE_SUB_TYPE) \ V(OBJECT_TO_CODE_SUB_TYPE) \ V(OPTIMIZED_CODE_LITERALS_SUB_TYPE) \ V(OPTIMIZED_CODE_MAP_SUB_TYPE) \ V(PROTOTYPE_USERS_SUB_TYPE) \ V(REGEXP_MULTIPLE_CACHE_SUB_TYPE) \ V(RETAINED_MAPS_SUB_TYPE) \ V(SCOPE_INFO_SUB_TYPE) \ V(SCRIPT_LIST_SUB_TYPE) \ V(SERIALIZED_OBJECTS_SUB_TYPE) \ V(SHARED_FUNCTION_INFOS_SUB_TYPE) \ V(SINGLE_CHARACTER_STRING_CACHE_SUB_TYPE) \ V(SLOW_TEMPLATE_INSTANTIATIONS_CACHE_SUB_TYPE) \ V(STRING_SPLIT_CACHE_SUB_TYPE) \ V(TEMPLATE_INFO_SUB_TYPE) \ V(FEEDBACK_METADATA_SUB_TYPE) \ V(WEAK_NEW_SPACE_OBJECT_TO_CODE_SUB_TYPE) enum FixedArraySubInstanceType { #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name, FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE) #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE LAST_FIXED_ARRAY_SUB_TYPE = WEAK_NEW_SPACE_OBJECT_TO_CODE_SUB_TYPE }; // Common superclass for FixedArrays that allow implementations to share // common accessors and some code paths. class FixedArrayBase : public TorqueGeneratedFixedArrayBase<FixedArrayBase, HeapObject> { public: // Get and set the length using acquire loads and release stores. DECL_SYNCHRONIZED_INT_ACCESSORS(length) inline Object unchecked_synchronized_length() const; static int GetMaxLengthForNewSpaceAllocation(ElementsKind kind); V8_EXPORT_PRIVATE bool IsCowArray() const; // Maximal allowed size, in bytes, of a single FixedArrayBase. // Prevents overflowing size computations, as well as extreme memory // consumption. It's either (512Mb - kTaggedSize) or (1024Mb - kTaggedSize). // -kTaggedSize is here to ensure that this max size always fits into Smi // which is necessary for being able to create a free space filler for the // whole array of kMaxSize. static const int kMaxSize = 128 * kTaggedSize * MB - kTaggedSize; STATIC_ASSERT(Smi::IsValid(kMaxSize)); protected: TQ_OBJECT_CONSTRUCTORS(FixedArrayBase) inline FixedArrayBase(Address ptr, HeapObject::AllowInlineSmiStorage allow_smi); }; // FixedArray describes fixed-sized arrays with element type Object. class FixedArray : public TorqueGeneratedFixedArray<FixedArray, FixedArrayBase> { public: // Setter and getter for elements. inline Object get(int index) const; inline Object get(const Isolate* isolate, int index) const; static inline Handle<Object> get(FixedArray array, int index, Isolate* isolate); // Return a grown copy if the index is bigger than the array's length. V8_EXPORT_PRIVATE static Handle<FixedArray> SetAndGrow( Isolate* isolate, Handle<FixedArray> array, int index, Handle<Object> value); // Synchronized setters and getters. inline Object synchronized_get(int index) const; inline Object synchronized_get(const Isolate* isolate, int index) const; // Currently only Smis are written with release semantics, hence we can avoid // a write barrier. inline void synchronized_set(int index, Smi value); // Setter that uses write barrier. inline void set(int index, Object value); inline bool is_the_hole(Isolate* isolate, int index); // Setter that doesn't need write barrier. inline void set(int index, Smi value); // Setter with explicit barrier mode. inline void set(int index, Object value, WriteBarrierMode mode); // Setters for frequently used oddballs located in old space. inline void set_undefined(int index); inline void set_undefined(Isolate* isolate, int index); inline void set_null(int index); inline void set_null(Isolate* isolate, int index); inline void set_the_hole(int index); inline void set_the_hole(Isolate* isolate, int index); inline ObjectSlot GetFirstElementAddress(); inline bool ContainsOnlySmisOrHoles(); // Gives access to raw memory which stores the array's data. inline ObjectSlot data_start(); inline void MoveElements(Isolate* isolate, int dst_index, int src_index, int len, WriteBarrierMode mode); inline void CopyElements(Isolate* isolate, int dst_index, FixedArray src, int src_index, int len, WriteBarrierMode mode); inline void FillWithHoles(int from, int to); // Shrink the array and insert filler objects. {new_length} must be > 0. V8_EXPORT_PRIVATE void Shrink(Isolate* isolate, int new_length); // If {new_length} is 0, return the canonical empty FixedArray. Otherwise // like above. static Handle<FixedArray> ShrinkOrEmpty(Isolate* isolate, Handle<FixedArray> array, int new_length); // Copy a sub array from the receiver to dest. V8_EXPORT_PRIVATE void CopyTo(int pos, FixedArray dest, int dest_pos, int len) const; // Garbage collection support. static constexpr int SizeFor(int length) { return kHeaderSize + length * kTaggedSize; } // Code Generation support. static constexpr int OffsetOfElementAt(int index) { STATIC_ASSERT(kObjectsOffset == SizeFor(0)); return SizeFor(index); } // Garbage collection support. inline ObjectSlot RawFieldOfElementAt(int index); // Maximally allowed length of a FixedArray. static const int kMaxLength = (kMaxSize - kHeaderSize) / kTaggedSize; static_assert(Internals::IsValidSmi(kMaxLength), "FixedArray maxLength not a Smi"); // Maximally allowed length for regular (non large object space) object. STATIC_ASSERT(kMaxRegularHeapObjectSize < kMaxSize); static const int kMaxRegularLength = (kMaxRegularHeapObjectSize - kHeaderSize) / kTaggedSize; // Dispatched behavior. DECL_PRINTER(FixedArray) int AllocatedSize(); class BodyDescriptor; static constexpr int kObjectsOffset = kHeaderSize; protected: // Set operation on FixedArray without using write barriers. Can // only be used for storing old space objects or smis. static inline void NoWriteBarrierSet(FixedArray array, int index, Object value); private: STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize); inline void set_undefined(ReadOnlyRoots ro_roots, int index); inline void set_null(ReadOnlyRoots ro_roots, int index); inline void set_the_hole(ReadOnlyRoots ro_roots, int index); TQ_OBJECT_CONSTRUCTORS(FixedArray) }; // FixedArray alias added only because of IsFixedArrayExact() predicate, which // checks for the exact instance type FIXED_ARRAY_TYPE instead of a range // check: [FIRST_FIXED_ARRAY_TYPE, LAST_FIXED_ARRAY_TYPE]. class FixedArrayExact final : public FixedArray {}; // FixedDoubleArray describes fixed-sized arrays with element type double. class FixedDoubleArray : public TorqueGeneratedFixedDoubleArray<FixedDoubleArray, FixedArrayBase> { public: // Setter and getter for elements. inline double get_scalar(int index); inline uint64_t get_representation(int index); static inline Handle<Object> get(FixedDoubleArray array, int index, Isolate* isolate); inline void set(int index, double value); inline void set_the_hole(Isolate* isolate, int index); inline void set_the_hole(int index); // Checking for the hole. inline bool is_the_hole(Isolate* isolate, int index); inline bool is_the_hole(int index); // Garbage collection support. inline static int SizeFor(int length) { return kHeaderSize + length * kDoubleSize; } inline void MoveElements(Isolate* isolate, int dst_index, int src_index, int len, WriteBarrierMode mode); inline void FillWithHoles(int from, int to); // Code Generation support. static int OffsetOfElementAt(int index) { return SizeFor(index); } // Start offset of elements. static constexpr int kFloatsOffset = kHeaderSize; // Maximally allowed length of a FixedDoubleArray. static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize; static_assert(Internals::IsValidSmi(kMaxLength), "FixedDoubleArray maxLength not a Smi"); // Dispatched behavior. DECL_PRINTER(FixedDoubleArray) DECL_VERIFIER(FixedDoubleArray) class BodyDescriptor; TQ_OBJECT_CONSTRUCTORS(FixedDoubleArray) }; // WeakFixedArray describes fixed-sized arrays with element type // MaybeObject. class WeakFixedArray : public TorqueGeneratedWeakFixedArray<WeakFixedArray, HeapObject> { public: inline MaybeObject Get(int index) const; inline MaybeObject Get(const Isolate* isolate, int index) const; inline void Set( int index, MaybeObject value, WriteBarrierMode mode = WriteBarrierMode::UPDATE_WRITE_BARRIER); // Get and set the length using acquire loads and release stores. DECL_SYNCHRONIZED_INT_ACCESSORS(length) // Gives access to raw memory which stores the array's data. inline MaybeObjectSlot data_start(); inline MaybeObjectSlot RawFieldOfElementAt(int index); inline void CopyElements(Isolate* isolate, int dst_index, WeakFixedArray src, int src_index, int len, WriteBarrierMode mode); DECL_PRINTER(WeakFixedArray) DECL_VERIFIER(WeakFixedArray) class BodyDescriptor; static const int kMaxLength = (FixedArray::kMaxSize - kHeaderSize) / kTaggedSize; static_assert(Internals::IsValidSmi(kMaxLength), "WeakFixedArray maxLength not a Smi"); int AllocatedSize(); static int OffsetOfElementAt(int index) { STATIC_ASSERT(kObjectsOffset == SizeFor(0)); return SizeFor(index); } private: friend class Heap; static const int kFirstIndex = 1; TQ_OBJECT_CONSTRUCTORS(WeakFixedArray) }; // WeakArrayList is like a WeakFixedArray with static convenience methods for // adding more elements. length() returns the number of elements in the list and // capacity() returns the allocated size. The number of elements is stored at // kLengthOffset and is updated with every insertion. The array grows // dynamically with O(1) amortized insertion. class WeakArrayList : public TorqueGeneratedWeakArrayList<WeakArrayList, HeapObject> { public: NEVER_READ_ONLY_SPACE DECL_PRINTER(WeakArrayList) V8_EXPORT_PRIVATE static Handle<WeakArrayList> AddToEnd( Isolate* isolate, Handle<WeakArrayList> array, const MaybeObjectHandle& value); // A version that adds to elements. This ensures that the elements are // inserted atomically w.r.t GC. V8_EXPORT_PRIVATE static Handle<WeakArrayList> AddToEnd( Isolate* isolate, Handle<WeakArrayList> array, const MaybeObjectHandle& value1, const MaybeObjectHandle& value2); // Appends an element to the array and possibly compacts and shrinks live weak // references to the start of the collection. Only use this method when // indices to elements can change. static Handle<WeakArrayList> Append( Isolate* isolate, Handle<WeakArrayList> array, const MaybeObjectHandle& value, AllocationType allocation = AllocationType::kYoung); // Compact weak references to the beginning of the array. V8_EXPORT_PRIVATE void Compact(Isolate* isolate); inline MaybeObject Get(int index) const; inline MaybeObject Get(const Isolate* isolate, int index) const; // Set the element at index to obj. The underlying array must be large enough. // If you need to grow the WeakArrayList, use the static AddToEnd() method // instead. inline void Set(int index, MaybeObject value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER); static constexpr int SizeForCapacity(int capacity) { return SizeFor(capacity); } static constexpr int CapacityForLength(int length) { return length + Max(length / 2, 2); } // Gives access to raw memory which stores the array's data. inline MaybeObjectSlot data_start(); inline void CopyElements(Isolate* isolate, int dst_index, WeakArrayList src, int src_index, int len, WriteBarrierMode mode); V8_EXPORT_PRIVATE bool IsFull(); // Get and set the capacity using acquire loads and release stores. DECL_SYNCHRONIZED_INT_ACCESSORS(capacity) int AllocatedSize(); class BodyDescriptor; static const int kMaxCapacity = (FixedArray::kMaxSize - kHeaderSize) / kTaggedSize; static Handle<WeakArrayList> EnsureSpace( Isolate* isolate, Handle<WeakArrayList> array, int length, AllocationType allocation = AllocationType::kYoung); // Returns the number of non-cleaned weak references in the array. int CountLiveWeakReferences() const; // Returns the number of non-cleaned elements in the array. int CountLiveElements() const; // Returns whether an entry was found and removed. Will move the elements // around in the array - this method can only be used in cases where the user // doesn't care about the indices! Users should make sure there are no // duplicates. V8_EXPORT_PRIVATE bool RemoveOne(const MaybeObjectHandle& value); class Iterator; private: static int OffsetOfElementAt(int index) { return kHeaderSize + index * kTaggedSize; } TQ_OBJECT_CONSTRUCTORS(WeakArrayList) }; class WeakArrayList::Iterator { public: explicit Iterator(WeakArrayList array) : index_(0), array_(array) {} inline HeapObject Next(); private: int index_; WeakArrayList array_; #ifdef DEBUG DisallowHeapAllocation no_gc_; #endif // DEBUG DISALLOW_COPY_AND_ASSIGN(Iterator); }; // Generic array grows dynamically with O(1) amortized insertion. // // ArrayList is a FixedArray with static convenience methods for adding more // elements. The Length() method returns the number of elements in the list, not // the allocated size. The number of elements is stored at kLengthIndex and is // updated with every insertion. The elements of the ArrayList are stored in the // underlying FixedArray starting at kFirstIndex. class ArrayList : public TorqueGeneratedArrayList<ArrayList, FixedArray> { public: V8_EXPORT_PRIVATE static Handle<ArrayList> Add(Isolate* isolate, Handle<ArrayList> array, Handle<Object> obj); V8_EXPORT_PRIVATE static Handle<ArrayList> Add(Isolate* isolate, Handle<ArrayList> array, Handle<Object> obj1, Handle<Object> obj2); static Handle<ArrayList> New(Isolate* isolate, int size); // Returns the number of elements in the list, not the allocated size, which // is length(). Lower and upper case length() return different results! inline int Length() const; // Sets the Length() as used by Elements(). Does not change the underlying // storage capacity, i.e., length(). inline void SetLength(int length); inline Object Get(int index) const; inline Object Get(const Isolate* isolate, int index) const; inline ObjectSlot Slot(int index); // Set the element at index to obj. The underlying array must be large enough. // If you need to grow the ArrayList, use the static Add() methods instead. inline void Set(int index, Object obj, WriteBarrierMode mode = UPDATE_WRITE_BARRIER); // Set the element at index to undefined. This does not change the Length(). inline void Clear(int index, Object undefined); // Return a copy of the list of size Length() without the first entry. The // number returned by Length() is stored in the first entry. static Handle<FixedArray> Elements(Isolate* isolate, Handle<ArrayList> array); static const int kHeaderFields = 1; private: static Handle<ArrayList> EnsureSpace(Isolate* isolate, Handle<ArrayList> array, int length); static const int kLengthIndex = 0; static const int kFirstIndex = 1; STATIC_ASSERT(kHeaderFields == kFirstIndex); TQ_OBJECT_CONSTRUCTORS(ArrayList) }; enum SearchMode { ALL_ENTRIES, VALID_ENTRIES }; template <SearchMode search_mode, typename T> inline int Search(T* array, Name name, int valid_entries = 0, int* out_insertion_index = nullptr, bool concurrent_search = false); // ByteArray represents fixed sized byte arrays. Used for the relocation info // that is attached to code objects. class ByteArray : public TorqueGeneratedByteArray<ByteArray, FixedArrayBase> { public: inline int Size(); // Setter and getter. inline byte get(int index) const; inline void set(int index, byte value); // Copy in / copy out whole byte slices. inline void copy_out(int index, byte* buffer, int length); inline void copy_in(int index, const byte* buffer, int length); // Treat contents as an int array. inline int get_int(int index) const; inline void set_int(int index, int value); inline uint32_t get_uint32(int index) const; inline void set_uint32(int index, uint32_t value); inline uint32_t get_uint32_relaxed(int index) const; inline void set_uint32_relaxed(int index, uint32_t value); // Clear uninitialized padding space. This ensures that the snapshot content // is deterministic. inline void clear_padding(); static int SizeFor(int length) { return OBJECT_POINTER_ALIGN(kHeaderSize + length); } // We use byte arrays for free blocks in the heap. Given a desired size in // bytes that is a multiple of the word size and big enough to hold a byte // array, this function returns the number of elements a byte array should // have. static int LengthFor(int size_in_bytes) { DCHECK(IsAligned(size_in_bytes, kTaggedSize)); DCHECK_GE(size_in_bytes, kHeaderSize); return size_in_bytes - kHeaderSize; } // Returns data start address. inline byte* GetDataStartAddress(); // Returns address of the past-the-end element. inline byte* GetDataEndAddress(); inline int DataSize() const; // Returns a pointer to the ByteArray object for a given data start address. static inline ByteArray FromDataStartAddress(Address address); // Dispatched behavior. inline int ByteArraySize(); DECL_PRINTER(ByteArray) // Layout description. static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize); // Maximal length of a single ByteArray. static const int kMaxLength = kMaxSize - kHeaderSize; static_assert(Internals::IsValidSmi(kMaxLength), "ByteArray maxLength not a Smi"); class BodyDescriptor; protected: TQ_OBJECT_CONSTRUCTORS(ByteArray) inline ByteArray(Address ptr, HeapObject::AllowInlineSmiStorage allow_smi); }; // Wrapper class for ByteArray which can store arbitrary C++ classes, as long // as they can be copied with memcpy. template <class T> class PodArray : public ByteArray { public: static Handle<PodArray<T>> New( Isolate* isolate, int length, AllocationType allocation = AllocationType::kYoung); void copy_out(int index, T* result, int length) { ByteArray::copy_out(index * sizeof(T), reinterpret_cast<byte*>(result), length * sizeof(T)); } void copy_in(int index, const T* buffer, int length) { ByteArray::copy_in(index * sizeof(T), reinterpret_cast<const byte*>(buffer), length * sizeof(T)); } bool matches(const T* buffer, int length) { DCHECK_LE(length, this->length()); return memcmp(GetDataStartAddress(), buffer, length * sizeof(T)) == 0; } T get(int index) { T result; copy_out(index, &result, 1); return result; } void set(int index, const T& value) { copy_in(index, &value, 1); } inline int length() const; DECL_CAST(PodArray<T>) OBJECT_CONSTRUCTORS(PodArray<T>, ByteArray); }; class TemplateList : public TorqueGeneratedTemplateList<TemplateList, FixedArray> { public: static Handle<TemplateList> New(Isolate* isolate, int size); inline int length() const; inline Object get(int index) const; inline Object get(const Isolate* isolate, int index) const; inline void set(int index, Object value); static Handle<TemplateList> Add(Isolate* isolate, Handle<TemplateList> list, Handle<Object> value); private: static const int kLengthIndex = 0; static const int kFirstElementIndex = kLengthIndex + 1; TQ_OBJECT_CONSTRUCTORS(TemplateList) }; } // namespace internal } // namespace v8 #include "src/objects/object-macros-undef.h" #endif // V8_OBJECTS_FIXED_ARRAY_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0efa5c9758b8bf3ccd9151e92d8d71d4a3414fe8
d2abe514518a3093bfa4e4f6693e02a31ca9aa46
/Physics for Students - VS12 LEAN/Game/SDKs/GeomUtils/src/GuConvexHull.h
b2c99f5459aee2ab4b22c57d39b8af423b4696d0
[]
no_license
stef52/Game-Dev-Class
a9a745019412dcb040cc9300c8c32a84e186e107
cc963f13adc1f6016c8a07036ef7709ce4445962
refs/heads/master
2020-05-27T21:57:51.113035
2015-04-08T19:17:25
2015-04-08T19:17:25
32,340,762
0
0
null
null
null
null
UTF-8
C++
false
false
2,754
h
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONVEXHULL_H #define GU_CONVEXHULL_H #include "PxPhysXCommonConfig.h" #include "PxVec3.h" #include "GuConvexMeshData.h" #include "GuSerialize.h" namespace physx { namespace Gu { struct ConvexHullData; PX_PHYSX_COMMON_API void initConvexHullData(ConvexHullData& data); PX_PHYSX_COMMON_API bool convexHullContains(const ConvexHullData& data, const PxVec3& p); PX_PHYSX_COMMON_API PxVec3 projectHull_( const ConvexHullData& hull, float& minimum, float& maximum, const PxVec3& localDir, const PxMat33& vert2ShapeSkew); PX_FORCE_INLINE void flipData(Gu::HullPolygonData& data) { data.mPlane.n.x = flip(&data.mPlane.n.x); data.mPlane.n.y = flip(&data.mPlane.n.y); data.mPlane.n.z = flip(&data.mPlane.n.z); data.mPlane.d = flip(&data.mPlane.d); data.mVRef8 = flip(&data.mVRef8); } // PT: if this one breaks, please make sure the 'flipData' function is properly updated. PX_COMPILE_TIME_ASSERT(sizeof(Gu::HullPolygonData) == 20); } } #endif // ICECONVEXHULL_H
[ "stephenbakalian@gmail.com" ]
stephenbakalian@gmail.com
b43e2ccebc3cf748f0cb7685be748e460826e7f6
466b6cc80d7496018369c1eb3d2796f506c37099
/table/Cell.h
0a3051b46e906f2ea7ee1bc31a02e87d64701afb
[]
no_license
CyanoFresh/oop-coursework-s3
7959da5c3f954a4c112f8287721885481f6c4464
a7bdaf31f291a9a5c8902861434cd4ae68c00d5a
refs/heads/master
2020-09-26T07:40:43.510968
2020-01-06T01:10:22
2020-01-06T01:10:22
210,690,052
0
0
null
null
null
null
UTF-8
C++
false
false
497
h
#ifndef COURSEWORK_CELL_H #define COURSEWORK_CELL_H #include "Object.h" #include <string> #include <iostream> namespace ATable { class Cell : public Object { private: unsigned int width; public: Cell(); ~Cell(); virtual string output() = 0; void print(ostream &stream); void setWidth(unsigned int width); unsigned int getWidth(); private: string boundary(string value); }; } #endif //COURSEWORK_CELL_H
[ "cyanofresh@gmail.com" ]
cyanofresh@gmail.com
9b35ac95aa44b47706e04a2070e0b2cbe6e1c385
4158d1aff880a2949ab032e5107773f4736d46f3
/Zappin' Kraken v1.0.6/src/main/include/Commands/Looped/FlipIntake.h
b6a21c068935e4d71f30302cfb30c5424056c24d
[]
no_license
FRC1410/infiniterecharge2020
37023c2af913ed1c6ecc9fa1c76310b589de35a2
00e0bf970debda2e1e232ff2261f6b489ba3a51c
refs/heads/master
2021-01-02T13:08:01.256723
2020-03-11T06:02:14
2020-03-11T06:02:14
239,635,589
5
4
null
2020-02-17T17:27:54
2020-02-10T23:32:11
C++
UTF-8
C++
false
false
265
h
#pragma once #include "Util/Libraries.h" class FlipIntake : public frc::Command { public: FlipIntake(); void Initialize() override; void Execute() override; bool IsFinished() override; void End() override; void Interrupted() override; };
[ "35178937+RandyNgo02@users.noreply.github.com" ]
35178937+RandyNgo02@users.noreply.github.com
89b56a27d163bbb2bff181e337297d5f2c54769a
019b1b4fc4a0c8bf0f65f5bec2431599e5de5300
/chrome/browser/ui/views/location_bar/content_setting_image_view.h
e6cc0d949eb7b53ece4770337b8ba3549c416418
[ "BSD-3-Clause" ]
permissive
wyrover/downloader
bd61b858d82ad437df36fbbaaf58d293f2f77445
a2239a4de6b8b545d6d88f6beccaad2b0c831e07
refs/heads/master
2020-12-30T14:45:13.193034
2017-04-23T07:39:04
2017-04-23T07:39:04
91,083,169
1
2
null
2017-05-12T11:06:42
2017-05-12T11:06:42
null
UTF-8
C++
false
false
4,012
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_CONTENT_SETTING_IMAGE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_CONTENT_SETTING_IMAGE_VIEW_H_ #include <memory> #include "base/macros.h" #include "chrome/browser/ui/content_settings/content_setting_image_model.h" #include "chrome/browser/ui/views/location_bar/icon_label_bubble_view.h" #include "components/content_settings/core/common/content_settings_types.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/animation/slide_animation.h" #include "ui/views/painter.h" #include "ui/views/view.h" #include "ui/views/widget/widget_observer.h" class ContentSettingImageModel; class LocationBarView; namespace content { class WebContents; } namespace gfx { class FontList; } namespace views { class BubbleDialogDelegateView; class ImageView; class InkDropDelegate; class Label; } // The ContentSettingImageView displays an icon and optional text label for // various content settings affordances in the location bar (i.e. plugin // blocking, geolocation). class ContentSettingImageView : public IconLabelBubbleView, public gfx::AnimationDelegate, public views::WidgetObserver { public: // ContentSettingImageView takes ownership of its |image_model|. ContentSettingImageView(ContentSettingImageModel* image_model, LocationBarView* parent, const gfx::FontList& font_list, SkColor parent_background_color); ~ContentSettingImageView() override; // Updates the decoration from the shown WebContents. void Update(content::WebContents* web_contents); private: // Number of milliseconds spent animating open; also the time spent animating // closed. static const int kOpenTimeMS; // The total animation time, including open and close as well as an // intervening "stay open" period. static const int kAnimationDurationMS; // IconLabelBubbleView: const char* GetClassName() const override; void OnBoundsChanged(const gfx::Rect& previous_bounds) override; bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; void OnNativeThemeChanged(const ui::NativeTheme* native_theme) override; SkColor GetTextColor() const override; SkColor GetBorderColor() const override; bool ShouldShowBackground() const override; double WidthMultiplier() const override; bool IsShrinking() const override; bool OnActivate() override; // gfx::AnimationDelegate: void AnimationEnded(const gfx::Animation* animation) override; void AnimationProgressed(const gfx::Animation* animation) override; void AnimationCanceled(const gfx::Animation* animation) override; // views::WidgetObserver: void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override; // Updates the image and tooltip to match the current model state. void UpdateImage(); LocationBarView* parent_; // Weak, owns us. std::unique_ptr<ContentSettingImageModel> content_setting_image_model_; gfx::SlideAnimation slide_animator_; bool pause_animation_; double pause_animation_state_; views::BubbleDialogDelegateView* bubble_view_; // This is used to check if the bubble was showing during the mouse pressed // event. If this is true then the mouse released event is ignored to prevent // the bubble from reshowing. bool suppress_mouse_released_action_; // Animation delegate for the ink drop ripple effect. std::unique_ptr<views::InkDropDelegate> ink_drop_delegate_; DISALLOW_COPY_AND_ASSIGN(ContentSettingImageView); }; #endif // CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_CONTENT_SETTING_IMAGE_VIEW_H_
[ "wangpp_os@sari.ac.cn" ]
wangpp_os@sari.ac.cn
51baa83fc2dc91d99a73b3ecbf00fc365b8a0f8a
9e0bc34d83ad3b4ea98163a209216d11c7860db6
/lshkit/trunk/3rd-party/boost/boost/throw_exception.hpp
69cdad0ccc54c21d25952fc1b3ff2b5b4080aa0c
[ "GPL-3.0-only", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-boost-original", "BSL-1.0", "LicenseRef-scancode-stlport-4.5" ]
permissive
wzj1695224/BinClone
07a00584f7b04bc1e6739cdc99d9fa0f4c812f8d
3b6dedb9a1f08be6dbcdce8f3278351ef5530ed8
refs/heads/master
2020-04-27T17:17:42.556516
2019-03-13T07:53:23
2019-03-13T07:53:23
174,512,239
0
0
Apache-2.0
2019-03-08T09:55:55
2019-03-08T09:55:55
null
UTF-8
C++
false
false
2,085
hpp
#ifndef BOOST_THROW_EXCEPTION_HPP_INCLUDED #define BOOST_THROW_EXCEPTION_HPP_INCLUDED // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif // // boost/throw_exception.hpp // // Copyright (c) 2002 Peter Dimov and Multi Media Ltd. // Copyright (c) 2008 Emil Dotchevski and Reverge Studios, Inc. // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // http://www.boost.org/libs/utility/throw_exception.html // #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <exception> #if !defined( BOOST_EXCEPTION_DISABLE ) && defined( __BORLANDC__ ) && BOOST_WORKAROUND( __BORLANDC__, BOOST_TESTED_AT(0x593) ) # define BOOST_EXCEPTION_DISABLE #endif #if !defined( BOOST_EXCEPTION_DISABLE ) && defined( BOOST_MSVC ) && BOOST_WORKAROUND( BOOST_MSVC, < 1310 ) # define BOOST_EXCEPTION_DISABLE #endif #if !defined( BOOST_NO_EXCEPTIONS ) && !defined( BOOST_EXCEPTION_DISABLE ) # include <boost/exception/exception.hpp> # include <boost/current_function.hpp> # define BOOST_THROW_EXCEPTION(x) ::boost::throw_exception(::boost::enable_error_info(x) <<\ ::boost::throw_function(BOOST_CURRENT_FUNCTION) <<\ ::boost::throw_file(__FILE__) <<\ ::boost::throw_line((int)__LINE__)) #else # define BOOST_THROW_EXCEPTION(x) ::boost::throw_exception(x) #endif namespace boost { #ifdef BOOST_NO_EXCEPTIONS void throw_exception( std::exception const & e ); // user defined #else inline void throw_exception_assert_compatibility( std::exception const & ) { } template<class E> inline void throw_exception( E const & e ) { //All boost exceptions are required to derive std::exception, //to ensure compatibility with BOOST_NO_EXCEPTIONS. throw_exception_assert_compatibility(e); #ifndef BOOST_EXCEPTION_DISABLE throw enable_current_exception(enable_error_info(e)); #else throw e; #endif } #endif } // namespace boost #endif // #ifndef BOOST_THROW_EXCEPTION_HPP_INCLUDED
[ "befung@gmail.com" ]
befung@gmail.com
5773171a4988c214d4bd066269fa21d6409c5896
7bba965199a6c44f26e283432b47ceae0f98ddef
/src/tests/render_formats.cpp
fe339c9e5c700d4a9a7fdc2d0278bba0ffcdccbc
[]
no_license
ameerj/nxgpucatch
d2f82c48e0bc9afc00305b1fdfec18221c6884e2
3198485217d74d48c655efd11117c3ba715f0dc8
refs/heads/master
2023-06-27T16:48:03.139706
2021-07-04T22:38:07
2021-07-04T22:38:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,424
cpp
#include <catch2/catch_test_macros.hpp> #include <deko3d.hpp> #include "cmd_util.h" #include "compare.h" #include "device.h" #include "resource.h" template <typename ClearInput, typename RefType> static bool Test(DkImageFormat format, const ClearInput& clear, const RefType& ref, typename RefType::value_type max_diff = {}) { RenderTarget2D render_target{format, 128, 128}; RecordRunWait([&](dk::CmdBuf cmdbuf) { render_target.Bind(cmdbuf); cmdbuf.setScissors(0, {DkScissor{0, 0, 128, 128}}); cmdbuf.clearColor(0, DkColorMask_RGBA, clear[0], clear[1], clear[2], clear[3]); }); return ThresholdCompare(render_target.Read<RefType>(64, 64), ref, max_diff); } TEST_CASE("R8_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_R8_Unorm, RGBA32F{0.5f}, R8U{127}, 1)); } TEST_CASE("R8_Snorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_R8_Snorm, RGBA32F{-1.0f}, R8I{-127}, 1)); } TEST_CASE("R8_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_R8_Uint, RGBA32U{0xccccccde}, R8U{255})); REQUIRE(Test(DkImageFormat_R8_Uint, RGBA32U{0xde}, R8U{0xde})); } TEST_CASE("R8_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_R8_Sint, RGBA32I{-500}, R8I{-128})); REQUIRE(Test(DkImageFormat_R8_Sint, RGBA32I{500}, R8I{127})); REQUIRE(Test(DkImageFormat_R8_Sint, RGBA32I{46}, R8I{46})); } TEST_CASE("R16_Float", "[render_formats]") { REQUIRE(Test(DkImageFormat_R16_Float, RGBA32F{1.0f}, R16F{1.0f})); REQUIRE(Test(DkImageFormat_R16_Float, RGBA32F{0.5f}, R16F{0.5f}, 0.5f)); REQUIRE(Test(DkImageFormat_R16_Float, RGBA32F{-8.0f}, R16F{-8.0f}, 0.5f)); } TEST_CASE("R16_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_R16_Unorm, RGBA32F{1.0f}, R16U{0xffff})); REQUIRE(Test(DkImageFormat_R16_Unorm, RGBA32F{0.5f}, R16U{0x7fff})); REQUIRE(Test(DkImageFormat_R16_Unorm, RGBA32F{-8.0f}, R16U{0})); } TEST_CASE("R16_Snorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_R16_Snorm, RGBA32F{1.0f}, R16I{0x7fff})); REQUIRE(Test(DkImageFormat_R16_Snorm, RGBA32F{0.5f}, R16I{0x3fff})); REQUIRE(Test(DkImageFormat_R16_Snorm, RGBA32F{-8.0f}, R16I{-0x7fff})); } TEST_CASE("R16_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_R16_Uint, RGBA32U{2020}, R16U{2020})); REQUIRE(Test(DkImageFormat_R16_Uint, RGBA32U{0x40000}, R16U{0xffff})); } TEST_CASE("R16_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_R16_Sint, RGBA32I{-2020}, R16I{-2020})); REQUIRE(Test(DkImageFormat_R16_Sint, RGBA32I{2020}, R16I{2020})); REQUIRE(Test(DkImageFormat_R16_Sint, RGBA32I{-0x10000}, R16I{-0x8000})); REQUIRE(Test(DkImageFormat_R16_Sint, RGBA32I{0x10000}, R16I{0x7fff})); } TEST_CASE("R32_Float", "[render_formats]") { REQUIRE(Test(DkImageFormat_R32_Float, RGBA32F{1.0f}, R32F{1.0f})); REQUIRE(Test(DkImageFormat_R32_Float, RGBA32F{-2.5f}, R32F{-2.5f}, 0.5f)); } TEST_CASE("R32_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_R32_Uint, RGBA32U{0xdeadbeef}, R32U{0xdeadbeef})); } TEST_CASE("R32_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_R32_Sint, RGBA32I{-0xcafe}, R32I{-0xcafe})); } TEST_CASE("RG8_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG8_Unorm, RGBA32F{1.5f, 0.5f}, RG8U{255, 127}, 1)); } TEST_CASE("RG8_Snorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG8_Snorm, RGBA32F{-1.5f, 1.5f}, RG8I{-127, 127})); REQUIRE(Test(DkImageFormat_RG8_Snorm, RGBA32F{0.0f, 0.5f}, RG8I{0, 127}, 1)); } TEST_CASE("RG8_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG8_Uint, RGBA32U{270, 7}, RG8U{255, 7})); } TEST_CASE("RG8_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG8_Sint, RGBA32I{270, -270}, RG8I{127, -128})); REQUIRE(Test(DkImageFormat_RG8_Sint, RGBA32I{8, -8}, RG8I{8, -8})); } TEST_CASE("RG16_Float", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG16_Float, RGBA32F{1.0f, -1.5f}, RG16F{1.0f, -1.5f}, 0.5f)); } TEST_CASE("RG16_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG16_Unorm, RGBA32F{1.5f, -1.5f}, RG16U{0xffff, 0})); REQUIRE(Test(DkImageFormat_RG16_Unorm, RGBA32F{0.5f, 0.0f}, RG16U{0x7fff, 0})); } TEST_CASE("RG16_Snorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG16_Snorm, RGBA32F{1.5f, -1.5f}, RG16I{0x7fff, -0x7fff})); REQUIRE(Test(DkImageFormat_RG16_Snorm, RGBA32F{0.5f, 0.0f}, RG16I{0x3fff, 0}, 1)); } TEST_CASE("RG16_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG16_Uint, RGBA32U{0x10000, 0xdead}, RG16U{0xffff, 0xdead})); } TEST_CASE("RG16_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG16_Sint, RGBA32I{-0x10000, 0x10000}, RG16I{-0x7fff, 0x7fff})); REQUIRE(Test(DkImageFormat_RG16_Sint, RGBA32I{-5050, 2020}, RG16I{-5050, 2020})); } TEST_CASE("RG32_Float", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG32_Float, RGBA32F{4.0f, -8.0f}, RG32F{4.0f, -8.0f}, 0.5f)); } TEST_CASE("RG32_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG32_Uint, RGBA32U{439, 0x80001234}, RG32U{439, 0x80001234})); } TEST_CASE("RG32_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RG32_Sint, RGBA32I{-439, 0x30001234}, RG32I{-439, 0x30001234})); } TEST_CASE("RGBA8_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA8_Unorm, RGBA32F{-1.0f, 0.0f, 1.0f, 0.5f}, RGBA8U{0, 0, 255, 127}, 1)); } TEST_CASE("RGBA8_Snorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA8_Snorm, RGBA32F{-1.0f, 0.0f, 1.0f, 0.0f}, RGBA8I{-127, 0, 127, 0}, 0)); REQUIRE( Test(DkImageFormat_RGBA8_Snorm, RGBA32F{-0.5f, 0, 0, .5f}, RGBA8I{-64, 0, 0, 64}, 1.0f)); } TEST_CASE("RGBA8_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA8_Uint, RGBA32U{280, 250, 210, 30}, RGBA8U{255, 250, 210, 30})); } TEST_CASE("RGBA8_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA8_Sint, RGBA32I{-280, 140, 5, -1}, RGBA8I{-127, 127, 5, -1})); } TEST_CASE("RGBA16_Float", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA16_Float, RGBA32F{4.0f, -8.0f, 1.0f, 16.0f}, RGBA16F{4.0f, -8.0f, 1.0f, 16.0f}, 0.5f)); } TEST_CASE("RGBA16_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA16_Unorm, RGBA32F{1.5f, 1.0f, 0.5f, 0.0f}, RGBA16U{0xffff, 0xffff, 0x7fff, 0}, 1)); } TEST_CASE("RGBA16_Snorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA16_Snorm, RGBA32F{1.5f, 1.0f, -1.0f, 0.5f}, RGBA16I{0x7fff, 0x7fff, -0x7fff, 0x3fff}, 1)); } TEST_CASE("RGBA16_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA16_Uint, RGBA32U{0x10000, 0x4000, 43, 891}, RGBA16U{0xffff, 0x4000, 43, 891})); } TEST_CASE("RGBA16_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA16_Sint, RGBA32I{0x8000, -0x8000, 43, -891}, RGBA16I{0x7fff, -0x7fff, 43, -891})); } TEST_CASE("RGBA32_Float", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA32_Float, RGBA32F{1.0f, 8.0f, -4.0f, -2.0f}, RGBA32F{1.0f, 8.0f, -4.0f, -2.0f}, 0.5f)); } TEST_CASE("RGBA32_Uint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA32_Uint, RGBA32U{1, 5, 0xdeadbeef, 54}, RGBA32U{1, 5, 0xdeadbeef, 54})); } TEST_CASE("RGBA32_Sint", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA32_Sint, RGBA32I{1, 5, -0x3eadbeef, 54}, RGBA32I{1, 5, -0x3eadbeef, 54})); } TEST_CASE("RGBX8_Unorm_sRGB", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBX8_Unorm_sRGB, RGBA32F{0.25f, 0.5f, 1.0f, 0.25f}, RGBA8U{137, 188, 255, 0}, 1)); } TEST_CASE("RGBA8_Unorm_sRGB", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBA8_Unorm_sRGB, RGBA32F{0.25f, 0.5f, 1.0f, 0.25f}, RGBA8U{137, 188, 255, 64}, 1)); } TEST_CASE("RGB10A2_Unorm", "[render_formats]") { RenderTarget2D render_target{DkImageFormat_RGB10A2_Unorm, 128, 128}; RecordRunWait([&](dk::CmdBuf cmdbuf) { render_target.Bind(cmdbuf); cmdbuf.setScissors(0, {DkScissor{0, 0, 128, 128}}); cmdbuf.clearColor(0, DkColorMask_RGBA, 1.0f, 1.0f, 1.0f, 0.0f); }); const auto sample1{render_target.Read<RGB10A2>(64, 64)}; REQUIRE(sample1.r == 1023); REQUIRE(sample1.g == 1023); REQUIRE(sample1.b == 1023); REQUIRE(sample1.a == 0); RecordRunWait([&](dk::CmdBuf cmdbuf) { cmdbuf.clearColor(0, DkColorMask_RGBA, 0.25f, 0.5f, 0.75f, 0.4f); }); const auto sample2{render_target.Read<RGB10A2>(64, 64)}; REQUIRE(ThresholdCompare<uint32_t>(sample2.r, 256, 1)); REQUIRE(ThresholdCompare<uint32_t>(sample2.g, 511, 1)); REQUIRE(ThresholdCompare<uint32_t>(sample2.b, 767, 1)); REQUIRE(ThresholdCompare<uint32_t>(sample2.a, 1, 0)); RecordRunWait([&](dk::CmdBuf cmdbuf) { cmdbuf.clearColor(0, DkColorMask_RGBA, 2.0f, -1.0f, 0.0f, 0.6f); }); const auto sample3{render_target.Read<RGB10A2>(64, 64)}; REQUIRE(ThresholdCompare<uint32_t>(sample3.r, 1023, 1)); REQUIRE(ThresholdCompare<uint32_t>(sample3.g, 0, 1)); REQUIRE(ThresholdCompare<uint32_t>(sample3.b, 0, 1)); REQUIRE(ThresholdCompare<uint32_t>(sample3.a, 2, 0)); } TEST_CASE("RG11B10_Float", "[render_formats]") { // RG11B10_Float is harder to test due to its low floating point precision // The asserts will compare against known good values to avoid conversions RenderTarget2D render_target{DkImageFormat_RG11B10_Float, 128, 128}; RecordRunWait([&](dk::CmdBuf cmdbuf) { render_target.Bind(cmdbuf); cmdbuf.setScissors(0, {DkScissor{0, 0, 128, 128}}); cmdbuf.clearColor(0, DkColorMask_RGBA, 1.0f, 0.0f, 1.0f, 1.0f); }); const auto sample1{render_target.Read<RG11B10>(64, 64)}; REQUIRE(sample1.r == 0x3c0); REQUIRE(sample1.g == 0); REQUIRE(sample1.b == 0x1e0); RecordRunWait( [&](dk::CmdBuf cmdbuf) { cmdbuf.clearColor(0, DkColorMask_RGBA, 0.0f, 1.0f, 0.0f, 1.0f); }); const auto sample2{render_target.Read<RG11B10>(64, 64)}; REQUIRE(sample2.r == 0); REQUIRE(sample2.g == 0x3c0); REQUIRE(sample2.b == 0); } TEST_CASE("RGBX8_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_RGBX8_Unorm, RGBA32F{0.25f, 0.5f, 1.0f, 0.25f}, RGBA8U{64, 127, 255, 0}, 1)); } TEST_CASE("RGBX8_Snorm", "[render_formats]") { // RGBX8_Snorm writes to alpha?! REQUIRE(Test(DkImageFormat_RGBX8_Snorm, RGBA32F{-0.5f, 1.0f, -2.0f, 0.5f}, RGBA8I{-31, 127, -127, 63}, 1)); } TEST_CASE("RGBX8_Uint", "[render_formats]") { // RGBX8_Uint writes to alpha too... REQUIRE(Test(DkImageFormat_RGBX8_Uint, RGBA32U{6, 280, 14, 36}, RGBA8U{6, 255, 14, 36}, 0)); } TEST_CASE("RGBX8_Sint", "[render_formats]") { // RGBX8_Sint writes to alpha REQUIRE( Test(DkImageFormat_RGBX8_Sint, RGBA32I{-6, 280, -240, 36}, RGBA8I{-6, 127, -128, 36}, 0)); } TEST_CASE("RGBX16_Float", "[render_formats]") { // Unlike previous formats, RGBX16_Float does .not. write to alpha REQUIRE(Test(DkImageFormat_RGBX16_Float, RGBA32F{1.0f, -8.0f, 4.0f, 2.0f}, RGBA16F{1.0f, -8.0f, 4.0f, 0.0f}, 0.5f)); } TEST_CASE("RGBX16_Unorm", "[render_formats]") { // But RGBX16_Unorm writes to alpha REQUIRE(Test(DkImageFormat_RGBX16_Unorm, RGBA32F{1.0f, -8.0f, 0.5f, 0.25f}, RGBA16U{0xffff, 0, 0x7fff, 0x4000}, 1)); } TEST_CASE("RGBX16_Snorm", "[render_formats]") { // RGBX16_Snorm also writes to alpha REQUIRE(Test(DkImageFormat_RGBX16_Snorm, RGBA32F{1.0f, -8.0f, 0.5f, 0.25f}, RGBA16I{0x7fff, -0x7fff, 0x4000, 0x2000}, 1)); } TEST_CASE("RGBX16_Uint", "[render_formats]") { // RGBX16_Uint writes to alpha REQUIRE(Test(DkImageFormat_RGBX16_Uint, RGBA32U{50, 0x10000, 13, 7}, RGBA16U{50, 0xffff, 13, 7}, 1)); } TEST_CASE("RGBX16_Sint", "[render_formats]") { // RGBX16_Sint writes to alpha REQUIRE(Test(DkImageFormat_RGBX16_Sint, RGBA32I{-0x10000, 0x10000, 19, -7}, RGBA16I{-0x7fff, 0x7fff, 19, -7}, 0)); } TEST_CASE("RGBX32_Float", "[render_formats]") { // RGBX32_Float does .not. write to alpha REQUIRE(Test(DkImageFormat_RGBX32_Float, RGBA32F{1.0f, 2.0f, -4.0f, 8.0f}, RGBA32F{1.0f, 2.0f, -4.0f, 0.0f}, 0.5f)); } TEST_CASE("RGBX32_Uint", "[render_formats]") { // RGBX32_Uint does .not. write to alpha REQUIRE(Test(DkImageFormat_RGBX32_Uint, RGBA32U{64, 0xdeadbeef, 934, 252}, RGBA32U{64, 0xdeadbeef, 934, 0})); } TEST_CASE("RGBX32_Sint", "[render_formats]") { // RGBX32_Sint does .not. write to alpha REQUIRE(Test(DkImageFormat_RGBX32_Sint, RGBA32I{-64, -0x3eadbeef, 934, -252}, RGBA32I{-64, -0x3eadbeef, 934, 0})); } TEST_CASE("BGR565_Unorm", "[render_formats]") { RenderTarget2D render_target{DkImageFormat_BGR565_Unorm, 128, 128}; RecordRunWait([&](dk::CmdBuf cmdbuf) { render_target.Bind(cmdbuf); cmdbuf.setScissors(0, {DkScissor{0, 0, 128, 128}}); cmdbuf.clearColor(0, DkColorMask_RGBA, 0.25f, 0.5f, 0.75f, 0.0f); }); const auto sample1{render_target.Read<BGR565>(64, 64)}; REQUIRE(ThresholdCompare<uint16_t>(sample1.r, 8, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample1.g, 31, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample1.b, 23, 1)); RecordRunWait([&](dk::CmdBuf cmdbuf) { cmdbuf.clearColor(0, DkColorMask_RGBA, -1.0f, 2.0f, 0.0f, 0.0f); }); const auto sample2{render_target.Read<BGR565>(64, 64)}; REQUIRE(ThresholdCompare<uint16_t>(sample2.r, 0, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample2.g, 63, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample2.b, 0, 1)); } TEST_CASE("BGR5_Unorm", "[render_formats]") { RenderTarget2D render_target{DkImageFormat_BGR5_Unorm, 128, 128}; RecordRunWait([&](dk::CmdBuf cmdbuf) { render_target.Bind(cmdbuf); cmdbuf.setScissors(0, {DkScissor{0, 0, 128, 128}}); cmdbuf.clearColor(0, DkColorMask_RGBA, 0.25f, 0.5f, 0.75f, 1.0f); }); const auto sample1{render_target.Read<BGR5A1>(64, 64)}; REQUIRE(ThresholdCompare<uint16_t>(sample1.r, 8, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample1.g, 15, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample1.b, 23, 1)); REQUIRE(sample1.a == 0); RecordRunWait([&](dk::CmdBuf cmdbuf) { cmdbuf.clearColor(0, DkColorMask_RGBA, -1.0f, 2.0f, 0.0f, 1.0f); }); const auto sample2{render_target.Read<BGR5A1>(64, 64)}; REQUIRE(ThresholdCompare<uint16_t>(sample2.r, 0, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample2.g, 31, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample2.b, 0, 1)); REQUIRE(sample2.a == 0); } TEST_CASE("BGR5A1_Unorm", "[render_formats]") { RenderTarget2D render_target{DkImageFormat_BGR5A1_Unorm, 128, 128}; RecordRunWait([&](dk::CmdBuf cmdbuf) { render_target.Bind(cmdbuf); cmdbuf.setScissors(0, {DkScissor{0, 0, 128, 128}}); cmdbuf.clearColor(0, DkColorMask_RGBA, 0.25f, 0.5f, 0.75f, 1.0f); }); const auto sample1{render_target.Read<BGR5A1>(64, 64)}; REQUIRE(ThresholdCompare<uint16_t>(sample1.r, 8, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample1.g, 15, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample1.b, 23, 1)); REQUIRE(sample1.a == 1); RecordRunWait([&](dk::CmdBuf cmdbuf) { cmdbuf.clearColor(0, DkColorMask_RGBA, -1.0f, 2.0f, 0.0f, 0.0f); }); const auto sample2{render_target.Read<BGR5A1>(64, 64)}; REQUIRE(ThresholdCompare<uint16_t>(sample2.r, 0, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample2.g, 31, 1)); REQUIRE(ThresholdCompare<uint16_t>(sample2.b, 0, 1)); REQUIRE(sample2.a == 0); } TEST_CASE("BGRX8_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_BGRX8_Unorm, RGBA32F{2.0f, 0.5f, 0.25f, 1.0f}, RGBA8U{64, 127, 255, 0}, 1)); } TEST_CASE("BGRA8_Unorm", "[render_formats]") { REQUIRE(Test(DkImageFormat_BGRA8_Unorm, RGBA32F{2.0f, 0.5f, 0.25f, 1.0f}, RGBA8U{64, 127, 255, 255}, 1)); } TEST_CASE("BGRX8_Unorm_sRGB", "[render_formats]") { REQUIRE(Test(DkImageFormat_BGRX8_Unorm_sRGB, RGBA32F{2.0f, 0.5f, 0.25f, 1.0f}, RGBA8U{137, 188, 255, 0}, 1)); } TEST_CASE("BGRA8_Unorm_sRGB", "[render_formats]") { REQUIRE(Test(DkImageFormat_BGRA8_Unorm_sRGB, RGBA32F{2.0f, 0.5f, 0.25f, 1.0f}, RGBA8U{137, 188, 255, 255}, 1)); }
[ "reinuseslisp@airmail.cc" ]
reinuseslisp@airmail.cc
62c15d7d8146171719101b921c8390e690790668
ac8e1fdf095656b31ebc6b5eb5e8e6f2c7688408
/TestCases/avrcppext/Actuators/RCServos/RCServoTest.h
648a97e73f73fece8118f7db1ae145702ca7d514
[ "MIT" ]
permissive
maxlem/AVRCpp
df7ed5328d41bff04bc2c40b052eea212003b699
63349326c7e326da2309d92857dd14735ef4f51d
refs/heads/main
2023-05-01T03:45:37.962711
2021-05-15T21:50:16
2021-05-15T22:25:01
367,734,753
0
0
null
null
null
null
UTF-8
C++
false
false
3,081
h
/* Copyright (c) 2007-2021 Maxime Lemonnier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef RCServoTest_H_ #define RCServoTest_H_ #include "TestCase.h" #include "Actuators/RCServos/RCServo.h" #include "Actuators/RCServos/PPMCapture.h" #include "Timers/Timer16bits3OCR.h" using Timers::Timer16bits3OCR; class RCServoTest : public TestCase<RCServoTest> { public: RCServoTest(const prog_mem * testMethodName_P, TestCase<RCServoTest>::TestMethod testMethod) : TestCase<RCServoTest>(testMethodName_P, testMethod) { Timer16bits3OCR * timer1 = Timer16bits3OCR::getTimer16bits3OCR(1); Timer16bits3OCR * timer4 = Timer16bits3OCR::getTimer16bits3OCR(4); timer1->getCapturer()->setICRValue(40000); // roughly 20ms, the standard servo duty cycle, that will be our TOP timer1->getComparatorA()->setOCROutputPinMode(Timers::CompareModes::CLEAR_OC_PIN_ON_COMPARE_MATCH); // the pulse start at 0, ends at OCRValue timer1->getComparatorA()->setOCRValue(3000); timer1->setWaveGenerationMode(1, 1, 1, 0); //Fast PWM, TOP == ICR timer1->getCounter()->setPrescaler(Timers::Prescalers::DIV_8); //with a 16Mhz clock, that will give us 8/16000000 = .5us per tick servo1A = new RCServo(timer1->getComparatorA(), &DDRB, PINB5, 2000, 4000); // the OCR values for 1ms, 1.5ms, 2ms timer4->getCounter()->setPrescaler(Timers::Prescalers::DIV_8); //with a 16Mhz clock, that will give us 8/16000000 = .5us per tick timer4->setWaveGenerationMode(0, 0, 0, 0); //Fast PWM, TOP == ICR capture3 = new PPMCapture(timer4->getCounter(), timer4->getCapturer(), 2.0, &DDRL, PINL0, 1); } void setUp() { } void tearDown() { } bool testsetPosition() { enableInterrupts(); uint16_t pulseWidth_us = 1000; //1ms int8_t increment = 10; while(true) { servo1A->setPulseWidth(pulseWidth_us); pulseWidth_us += increment; if(pulseWidth_us < 1000 || pulseWidth_us > 2000) increment = -increment; printf("ch0 = %d\r", capture3->getPulseWidth(0)); } disableInterrupts(); } protected : RCServo * servo1A; PPMCapture * capture3; }; #endif /* RCServoTest_H_ */
[ "maxime.lemonnier@gmail.com" ]
maxime.lemonnier@gmail.com
43e6efc80f14c1acdf78fcd4129bfd053fd61f01
ae22c23f30161b23be7f5568e89efbb94b7e5cca
/src/circuit/task/builder/StoreTask.cpp
fe4ff49f7eed400fe92d99a85a153da9372fdc76
[]
no_license
cleanrock/CircuitAI
9c68d906c02d3dd0a7173178a6b7f6d9aefc7da5
d4d7fd5f147cd557f7083a232446ba5329aa478c
refs/heads/master
2020-04-07T23:59:45.940002
2016-02-26T19:43:39
2016-02-26T19:43:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
/* * StoreTask.cpp * * Created on: Jan 30, 2015 * Author: rlcevg */ #include "task/builder/StoreTask.h" #include "util/utils.h" namespace circuit { using namespace springai; CBStoreTask::CBStoreTask(ITaskManager* mgr, Priority priority, CCircuitDef* buildDef, const AIFloat3& position, float cost, float shake, int timeout) : IBuilderTask(mgr, priority, buildDef, position, BuildType::STORE, cost, shake, timeout) { } CBStoreTask::~CBStoreTask() { PRINT_DEBUG("Execute: %s\n", __PRETTY_FUNCTION__); } } // namespace circuit
[ "rlcevg@gmail.com" ]
rlcevg@gmail.com
71d28f423c3f325f72343f17eac00d96b0e3a9ae
0150d34d5ced4266b6606c87fbc389f23ed19a45
/Cpp/SDK/UMG_Scoreboard_parameters.h
602e0ec8a0fc2eeb65b94613ed58896ecf1e042e
[ "Apache-2.0" ]
permissive
joey00186/Squad-SDK
9aa1b6424d4e5b0a743e105407934edea87cbfeb
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
refs/heads/master
2023-02-05T19:00:05.452463
2021-01-03T19:03:34
2021-01-03T19:03:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
h
#pragma once // Name: S, Version: b #include "../SDK.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function UMG_Scoreboard.UMG_Scoreboard_C.UpdateScaling struct UUMG_Scoreboard_C_UpdateScaling_Params { }; // Function UMG_Scoreboard.UMG_Scoreboard_C.UpdateServerFPSText struct UUMG_Scoreboard_C_UpdateServerFPSText_Params { }; // Function UMG_Scoreboard.UMG_Scoreboard_C.Construct struct UUMG_Scoreboard_C_Construct_Params { }; // Function UMG_Scoreboard.UMG_Scoreboard_C.BPInit struct UUMG_Scoreboard_C_BPInit_Params { }; // Function UMG_Scoreboard.UMG_Scoreboard_C.CustomTickEvent struct UUMG_Scoreboard_C_CustomTickEvent_Params { }; // Function UMG_Scoreboard.UMG_Scoreboard_C.BndEvt__MainMenu_Button_K2Node_ComponentBoundEvent_0_OnClicked__DelegateSignature struct UUMG_Scoreboard_C_BndEvt__MainMenu_Button_K2Node_ComponentBoundEvent_0_OnClicked__DelegateSignature_Params { bool bSelected; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor) class UMainMenu_Button_C* Button; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; // Function UMG_Scoreboard.UMG_Scoreboard_C.Play Fade Animation struct UUMG_Scoreboard_C_Play_Fade_Animation_Params { }; // Function UMG_Scoreboard.UMG_Scoreboard_C.Destruct struct UUMG_Scoreboard_C_Destruct_Params { }; // Function UMG_Scoreboard.UMG_Scoreboard_C.ExecuteUbergraph_UMG_Scoreboard struct UUMG_Scoreboard_C_ExecuteUbergraph_UMG_Scoreboard_Params { int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "tahmaniak@gmail.com" ]
tahmaniak@gmail.com
5babebe2770abff17a070dfa3ac7c32bf63b580b
83f68c623b2163fc33c88be63d93a51c0c902b80
/C++/bullet3-2.83.5/bullet3-2.83.5/src/BulletCollision/CollisionShapes/btTriangleMeshShape.h
903decf45092ffd7f6f0f3adf93db9931886f964
[ "Zlib" ]
permissive
AlexStopar/SnowyFogSample
e2673a67b69e4e6cd04b39bee81f55ca0ef2ca9e
9844426c3485a042ff7322a62e2a4970c7ac6490
refs/heads/master
2021-01-10T19:17:19.912203
2015-08-23T20:55:29
2015-08-23T20:55:29
41,267,020
0
0
null
null
null
null
UTF-8
C++
false
false
2,818
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_TRIANGLE_MESH_SHAPE_H #define BT_TRIANGLE_MESH_SHAPE_H #include "btConcaveShape.h" #include "btStridingMeshInterface.h" ///The btTriangleMeshShape is an internal concave triangle mesh interface. Don't use this class directly, use btBvhTriangleMeshShape instead. ATTRIBUTE_ALIGNED16(class) btTriangleMeshShape : public btConcaveShape { protected: btVector3 m_localAabbMin; btVector3 m_localAabbMax; btStridingMeshInterface* m_meshInterface; ///btTriangleMeshShape constructor has been disabled/protected, so that users will not mistakenly use this class. ///Don't use btTriangleMeshShape but use btBvhTriangleMeshShape instead! btTriangleMeshShape(btStridingMeshInterface* meshInterface); public: BT_DECLARE_ALIGNED_ALLOCATOR(); virtual ~btTriangleMeshShape(); virtual btVector3 localGetSupportingVertex(const btVector3& vec) const; virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const { int x = 0; btAssert(x); return localGetSupportingVertex(vec); } void recalcLocalAabb(); virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual void setLocalScaling(const btVector3& scaling); virtual const btVector3& getLocalScaling() const; btStridingMeshInterface* getMeshInterface() { return m_meshInterface; } const btStridingMeshInterface* getMeshInterface() const { return m_meshInterface; } const btVector3& getLocalAabbMin() const { return m_localAabbMin; } const btVector3& getLocalAabbMax() const { return m_localAabbMax; } //debugging virtual const char* getName()const {return "TRIANGLEMESH";} }; #endif //BT_TRIANGLE_MESH_SHAPE_H
[ "stopar.2@osu.edu" ]
stopar.2@osu.edu
b9400d5f81f84283a29adc4e3fb6141b5c5c6f0e
ad62d5a6236c35d71a647802cf4d6d2ead2558a8
/tests/UnitTests/TestBlockchainExplorer.cpp
5287d2b242468b54e136d55895e1d67e47c844af
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
cycere/quid
7af570e6d2fd6a8e4cbd5c5253060c76c488bd72
889b5bd36339d4e632c07a037db9ba38bf89ea30
refs/heads/master
2023-01-21T22:13:08.580206
2020-12-01T00:00:40
2020-12-01T00:00:40
316,043,120
0
0
null
null
null
null
UTF-8
C++
false
false
41,130
cpp
// Copyright (c) 2011-2016 The Cryptonote developers // Copyright (c) 2017-2021 The Cycere developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include <system_error> #include <boost/range/combine.hpp> #include "EventWaiter.h" #include "ICoreStub.h" #include "IQuidProtocolQueryStub.h" #include "INodeStubs.h" #include "QuidCore/TransactionApi.h" #include "TestBlockchainGenerator.h" #include "QuidCore/QuidTools.h" #include "Logging/FileLogger.h" #include "BlockchainExplorer/BlockchainExplorer.h" using namespace Crypto; using namespace Quid; namespace { Transaction createTx(ITransactionReader& tx) { Transaction outTx; fromBinaryArray(outTx, tx.getTransactionData()); return outTx; } } struct CallbackStatus { CallbackStatus() {} bool wait() { return waiter.wait_for(std::chrono::milliseconds(3000)); } bool ok() { return waiter.wait_for(std::chrono::milliseconds(3000)) && !static_cast<bool>(code); } void setStatus(const std::error_code& ec) { code = ec; waiter.notify(); } std::error_code getStatus() const { return code; } std::error_code code; EventWaiter waiter; }; class dummyObserver : public IBlockchainObserver { public: virtual ~dummyObserver() {} }; class smartObserver : public IBlockchainObserver { public: virtual ~smartObserver() {} virtual void blockchainUpdated(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) override { blockchainUpdatedCallback(newBlocks, orphanedBlocks); } virtual void poolUpdated(const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) override { poolUpdatedCallback(newTransactions, removedTransactions); } virtual void blockchainSynchronized(const BlockDetails& topBlock) override { blockchainSynchronizedCallback(topBlock); } void setCallback(const std::function<void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks)>& cb) { blockchainUpdatedCallback = cb; } void setCallback(const std::function<void(const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions)>& cb) { poolUpdatedCallback = cb; } void setCallback(std::function<void(const BlockDetails& topBlock)>& cb) { blockchainSynchronizedCallback = cb; } private: std::function<void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks)> blockchainUpdatedCallback; std::function<void(const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions)> poolUpdatedCallback; std::function<void(const BlockDetails& topBlock)> blockchainSynchronizedCallback; }; class BlockchainExplorerTests : public ::testing::Test { public: BlockchainExplorerTests() : currency(CurrencyBuilder(logger).currency()), generator(currency), nodeStub(generator), blockchainExplorer(nodeStub, logger) { } void SetUp() override; void TearDown() override; protected: Currency currency; TestBlockchainGenerator generator; INodeTrivialRefreshStub nodeStub; Logging::FileLogger logger; dummyObserver observer; BlockchainExplorer blockchainExplorer; }; void BlockchainExplorerTests::SetUp() { logger.init("/dev/null"); ASSERT_NO_THROW(blockchainExplorer.init()); } void BlockchainExplorerTests::TearDown() { ASSERT_NO_THROW(blockchainExplorer.shutdown()); } TEST_F(BlockchainExplorerTests, initOk) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_NO_THROW(newExplorer.init()); } TEST_F(BlockchainExplorerTests, shutdownOk) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_NO_THROW(newExplorer.init()); ASSERT_NO_THROW(newExplorer.shutdown()); } TEST_F(BlockchainExplorerTests, doubleInit) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_NO_THROW(newExplorer.init()); ASSERT_ANY_THROW(newExplorer.init()); } TEST_F(BlockchainExplorerTests, shutdownNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.shutdown()); } TEST_F(BlockchainExplorerTests, addObserver) { ASSERT_TRUE(blockchainExplorer.addObserver(&observer)); } TEST_F(BlockchainExplorerTests, addObserverNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.addObserver(&observer)); } TEST_F(BlockchainExplorerTests, removeObserver) { ASSERT_TRUE(blockchainExplorer.addObserver(&observer)); ASSERT_TRUE(blockchainExplorer.removeObserver(&observer)); } TEST_F(BlockchainExplorerTests, removeObserverNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.addObserver(&observer)); ASSERT_ANY_THROW(newExplorer.removeObserver(&observer)); } TEST_F(BlockchainExplorerTests, removeObserverNotAdded) { ASSERT_FALSE(blockchainExplorer.removeObserver(&observer)); } TEST_F(BlockchainExplorerTests, getBlocksByHeightGenesis) { std::vector<uint32_t> blockHeights; blockHeights.push_back(0); std::vector<std::vector<BlockDetails>> blocks; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlocks(blockHeights, blocks)); ASSERT_EQ(blocks.size(), 1); EXPECT_EQ(blockHeights.size(), blocks.size()); ASSERT_EQ(blocks.front().size(), 1); EXPECT_EQ(blocks.front().front().height, 0); EXPECT_FALSE(blocks.front().front().isOrphaned); } TEST_F(BlockchainExplorerTests, getBlocksByHeightMany) { const uint32_t NUMBER_OF_BLOCKS = 10; std::vector<uint32_t> blockHeights; for (uint32_t i = 0; i < NUMBER_OF_BLOCKS; ++i) { blockHeights.push_back(i); } std::vector<std::vector<BlockDetails>> blocks; generator.generateEmptyBlocks(NUMBER_OF_BLOCKS); ASSERT_GE(generator.getBlockchain().size(), NUMBER_OF_BLOCKS); ASSERT_TRUE(blockchainExplorer.getBlocks(blockHeights, blocks)); EXPECT_EQ(blocks.size(), NUMBER_OF_BLOCKS); ASSERT_EQ(blockHeights.size(), blocks.size()); auto range = boost::combine(blockHeights, blocks); for (const boost::tuple<size_t, std::vector<BlockDetails>>& sameHeight : range) { EXPECT_EQ(sameHeight.get<1>().size(), 1); for (const BlockDetails& block : sameHeight.get<1>()) { EXPECT_EQ(block.height, sameHeight.get<0>()); EXPECT_FALSE(block.isOrphaned); } } } TEST_F(BlockchainExplorerTests, getBlocksByHeightFail) { const uint32_t NUMBER_OF_BLOCKS = 10; std::vector<uint32_t> blockHeights; for (uint32_t i = 0; i < NUMBER_OF_BLOCKS; ++i) { blockHeights.push_back(i); } std::vector<std::vector<BlockDetails>> blocks; EXPECT_LT(generator.getBlockchain().size(), NUMBER_OF_BLOCKS); ASSERT_ANY_THROW(blockchainExplorer.getBlocks(blockHeights, blocks)); } TEST_F(BlockchainExplorerTests, getBlocksByHeightNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); std::vector<uint32_t> blockHeights; blockHeights.push_back(0); std::vector<std::vector<BlockDetails>> blocks; ASSERT_ANY_THROW(newExplorer.getBlocks(blockHeights, blocks)); } TEST_F(BlockchainExplorerTests, getBlocksByHashGenesis) { std::vector<Hash> blockHashes; ASSERT_GE(generator.getBlockchain().size(), 1); Hash genesisHash = get_block_hash(generator.getBlockchain().front()); blockHashes.push_back(genesisHash); std::vector<BlockDetails> blocks; ASSERT_TRUE(blockchainExplorer.getBlocks(blockHashes, blocks)); ASSERT_EQ(blocks.size(), 1); EXPECT_EQ(blockHashes.size(), blocks.size()); Hash expectedHash = genesisHash; EXPECT_EQ(blocks.front().hash, expectedHash); EXPECT_EQ(blocks.front().hash, blockHashes.front()); EXPECT_FALSE(blocks.front().isOrphaned); } TEST_F(BlockchainExplorerTests, getBlocksByHashMany) { const size_t NUMBER_OF_BLOCKS = 10; std::vector<Hash> blockHashes; generator.generateEmptyBlocks(NUMBER_OF_BLOCKS); ASSERT_GE(generator.getBlockchain().size(), NUMBER_OF_BLOCKS); for (const auto& block : generator.getBlockchain()) { if (blockHashes.size() == NUMBER_OF_BLOCKS) { break; } Hash hash = get_block_hash(block); blockHashes.push_back(hash); } std::vector<BlockDetails> blocks; ASSERT_TRUE(blockchainExplorer.getBlocks(blockHashes, blocks)); EXPECT_EQ(blocks.size(), NUMBER_OF_BLOCKS); ASSERT_EQ(blockHashes.size(), blocks.size()); auto range = boost::combine(blockHashes, blocks); for (const boost::tuple<Hash, BlockDetails>& hashWithBlock : range) { EXPECT_EQ(hashWithBlock.get<0>(), hashWithBlock.get<1>().hash); EXPECT_FALSE(hashWithBlock.get<1>().isOrphaned); } } TEST_F(BlockchainExplorerTests, getBlocksByHashFail) { const size_t NUMBER_OF_BLOCKS = 10; std::vector<Hash> blockHashes; for (size_t i = 0; i < NUMBER_OF_BLOCKS; ++i) { blockHashes.push_back(boost::value_initialized<Hash>()); } std::vector<BlockDetails> blocks; EXPECT_LT(generator.getBlockchain().size(), NUMBER_OF_BLOCKS); ASSERT_ANY_THROW(blockchainExplorer.getBlocks(blockHashes, blocks)); } TEST_F(BlockchainExplorerTests, getBlocksByHashNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); std::vector<Hash> blockHashes; Hash genesisHash = get_block_hash(generator.getBlockchain().front()); blockHashes.push_back(genesisHash); std::vector<BlockDetails> blocks; ASSERT_ANY_THROW(newExplorer.getBlocks(blockHashes, blocks)); } TEST_F(BlockchainExplorerTests, getBlockchainTop) { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); } TEST_F(BlockchainExplorerTests, getBlockchainTopNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_ANY_THROW(newExplorer.getBlockchainTop(topBlock)); } TEST_F(BlockchainExplorerTests, getTransactionFromBlockchain) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); generator.addTxToBlockchain(tx); ASSERT_GE(generator.getBlockchain().size(), 1); std::vector<Hash> transactionHashes; Hash hash = getObjectHash(tx); transactionHashes.push_back(hash); std::vector<TransactionDetails> transactions; ASSERT_TRUE(blockchainExplorer.getTransactions(transactionHashes, transactions)); ASSERT_EQ(transactions.size(), 1); EXPECT_EQ(transactions.size(), transactionHashes.size()); EXPECT_EQ(transactions.front().hash, transactionHashes.front()); EXPECT_TRUE(transactions.front().inBlockchain); } TEST_F(BlockchainExplorerTests, getTransactionFromPool) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); generator.putTxToPool(tx); ASSERT_GE(generator.getBlockchain().size(), 1); std::vector<Hash> transactionHashes; Hash hash = getObjectHash(tx); transactionHashes.push_back(hash); std::vector<TransactionDetails> transactions; ASSERT_TRUE(blockchainExplorer.getTransactions(transactionHashes, transactions)); ASSERT_EQ(transactions.size(), 1); EXPECT_EQ(transactions.size(), transactionHashes.size()); EXPECT_EQ(transactions.front().hash, transactionHashes.front()); EXPECT_FALSE(transactions.front().inBlockchain); } TEST_F(BlockchainExplorerTests, getTransactionsMany) { size_t POOL_TX_NUMBER = 10; size_t BLOCKCHAIN_TX_NUMBER = 10; std::vector<Hash> poolTxs; std::vector<Hash> blockchainTxs; for (size_t i = 0; i < POOL_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); poolTxs.push_back(hash); generator.putTxToPool(tx); } for (size_t i = 0; i < BLOCKCHAIN_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); blockchainTxs.push_back(hash); generator.addTxToBlockchain(tx); } ASSERT_GE(generator.getBlockchain().size(), 1); std::vector<Hash> transactionHashes; std::copy(poolTxs.begin(), poolTxs.end(), std::back_inserter(transactionHashes)); std::copy(blockchainTxs.begin(), blockchainTxs.end(), std::back_inserter(transactionHashes)); std::vector<TransactionDetails> transactions; ASSERT_TRUE(blockchainExplorer.getTransactions(transactionHashes, transactions)); ASSERT_EQ(transactions.size(), POOL_TX_NUMBER + BLOCKCHAIN_TX_NUMBER); EXPECT_EQ(transactions.size(), transactionHashes.size()); for (const Hash& poolTxHash : poolTxs) { auto iter = std::find_if( transactions.begin(), transactions.end(), [&poolTxHash](const TransactionDetails& txDetails) -> bool { return poolTxHash == txDetails.hash; } ); EXPECT_NE(iter, transactions.end()); EXPECT_EQ(iter->hash, poolTxHash); EXPECT_FALSE(iter->inBlockchain); } for (const Hash& blockchainTxHash : blockchainTxs) { auto iter = std::find_if( transactions.begin(), transactions.end(), [&blockchainTxHash](const TransactionDetails& txDetails) -> bool { return blockchainTxHash == txDetails.hash; } ); EXPECT_NE(iter, transactions.end()); EXPECT_EQ(iter->hash, blockchainTxHash); EXPECT_TRUE(iter->inBlockchain); } } TEST_F(BlockchainExplorerTests, getTransactionsFail) { size_t POOL_TX_NUMBER = 10; size_t BLOCKCHAIN_TX_NUMBER = 10; std::vector<Hash> poolTxs; std::vector<Hash> blockchainTxs; for (size_t i = 0; i < POOL_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); poolTxs.push_back(hash); generator.putTxToPool(tx); } for (size_t i = 0; i < BLOCKCHAIN_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); blockchainTxs.push_back(hash); generator.addTxToBlockchain(tx); } ASSERT_GE(generator.getBlockchain().size(), 1); std::vector<Hash> transactionHashes; transactionHashes.push_back(boost::value_initialized<Hash>()); std::vector<TransactionDetails> transactions; ASSERT_ANY_THROW(blockchainExplorer.getTransactions(transactionHashes, transactions)); } TEST_F(BlockchainExplorerTests, getTransactionsNotInited) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); generator.addTxToBlockchain(tx); ASSERT_GE(generator.getBlockchain().size(), 1); std::vector<Hash> transactionHashes; Hash hash = getObjectHash(tx); transactionHashes.push_back(hash); std::vector<TransactionDetails> transactions; BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.getTransactions(transactionHashes, transactions)); } TEST_F(BlockchainExplorerTests, getPoolStateEmpty) { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); std::vector<Hash> knownPoolTransactionHashes; Hash knownBlockchainTop = topBlock.hash; bool isBlockchainActual; std::vector<TransactionDetails> newTransactions; std::vector<Hash> removedTransactions; ASSERT_TRUE(blockchainExplorer.getPoolState(knownPoolTransactionHashes, knownBlockchainTop, isBlockchainActual, newTransactions, removedTransactions)); EXPECT_TRUE(isBlockchainActual); EXPECT_EQ(newTransactions.size(), 0); EXPECT_EQ(removedTransactions.size(), 0); } TEST_F(BlockchainExplorerTests, getPoolStateMany) { size_t POOL_TX_NUMBER = 10; std::vector<Hash> poolTxs; for (size_t i = 0; i < POOL_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); poolTxs.push_back(hash); generator.putTxToPool(tx); } { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); std::vector<Hash> knownPoolTransactionHashes; Hash knownBlockchainTop = topBlock.hash; bool isBlockchainActual; std::vector<TransactionDetails> newTransactions; std::vector<Hash> removedTransactions; ASSERT_TRUE(blockchainExplorer.getPoolState(knownPoolTransactionHashes, knownBlockchainTop, isBlockchainActual, newTransactions, removedTransactions)); EXPECT_TRUE(isBlockchainActual); EXPECT_EQ(newTransactions.size(), POOL_TX_NUMBER); EXPECT_EQ(removedTransactions.size(), 0); for (const Hash& poolTxHash : poolTxs) { auto iter = std::find_if( newTransactions.begin(), newTransactions.end(), [&poolTxHash](const TransactionDetails& txDetails) -> bool { return poolTxHash == txDetails.hash; } ); EXPECT_NE(iter, newTransactions.end()); EXPECT_EQ(iter->hash, poolTxHash); EXPECT_FALSE(iter->inBlockchain); } } generator.putTxPoolToBlockchain(); { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); std::vector<Hash> knownPoolTransactionHashes; Hash knownBlockchainTop = topBlock.hash; bool isBlockchainActual; std::vector<TransactionDetails> newTransactions; std::vector<Hash> removedTransactions; ASSERT_TRUE(blockchainExplorer.getPoolState(knownPoolTransactionHashes, knownBlockchainTop, isBlockchainActual, newTransactions, removedTransactions)); EXPECT_TRUE(isBlockchainActual); EXPECT_EQ(newTransactions.size(), 0); EXPECT_EQ(removedTransactions.size(), 0); } { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); std::vector<Hash> knownPoolTransactionHashes = poolTxs; Hash knownBlockchainTop = topBlock.hash; bool isBlockchainActual; std::vector<TransactionDetails> newTransactions; std::vector<Hash> removedTransactions; ASSERT_TRUE(blockchainExplorer.getPoolState(knownPoolTransactionHashes, knownBlockchainTop, isBlockchainActual, newTransactions, removedTransactions)); EXPECT_TRUE(isBlockchainActual); EXPECT_EQ(newTransactions.size(), 0); EXPECT_EQ(removedTransactions.size(), POOL_TX_NUMBER); for (const Hash& poolTxHash : knownPoolTransactionHashes) { auto iter = std::find( removedTransactions.begin(), removedTransactions.end(), poolTxHash ); EXPECT_NE(iter, removedTransactions.end()); EXPECT_EQ(*iter, poolTxHash); } } auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash newTxHash = getObjectHash(tx); generator.putTxToPool(tx); { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); std::vector<Hash> knownPoolTransactionHashes = poolTxs; Hash knownBlockchainTop = topBlock.hash; bool isBlockchainActual; std::vector<TransactionDetails> newTransactions; std::vector<Hash> removedTransactions; ASSERT_TRUE(blockchainExplorer.getPoolState(knownPoolTransactionHashes, knownBlockchainTop, isBlockchainActual, newTransactions, removedTransactions)); EXPECT_TRUE(isBlockchainActual); ASSERT_EQ(newTransactions.size(), 1); EXPECT_EQ(newTransactions.front().hash, newTxHash); EXPECT_EQ(removedTransactions.size(), POOL_TX_NUMBER); for (const Hash& poolTxHash : knownPoolTransactionHashes) { auto iter = std::find( removedTransactions.begin(), removedTransactions.end(), poolTxHash ); EXPECT_NE(iter, removedTransactions.end()); EXPECT_EQ(*iter, poolTxHash); } } { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); std::vector<Hash> knownPoolTransactionHashes; Hash knownBlockchainTop = boost::value_initialized<Hash>(); bool isBlockchainActual; std::vector<TransactionDetails> newTransactions; std::vector<Hash> removedTransactions; ASSERT_TRUE(blockchainExplorer.getPoolState(knownPoolTransactionHashes, knownBlockchainTop, isBlockchainActual, newTransactions, removedTransactions)); EXPECT_FALSE(isBlockchainActual); } } TEST_F(BlockchainExplorerTests, getPoolStateNotInited) { std::vector<Hash> knownPoolTransactionHashes; Hash knownBlockchainTop = boost::value_initialized<Hash>(); bool isBlockchainActual; std::vector<TransactionDetails> newTransactions; std::vector<Hash> removedTransactions; BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.getPoolState(knownPoolTransactionHashes, knownBlockchainTop, isBlockchainActual, newTransactions, removedTransactions)); } TEST_F(BlockchainExplorerTests, getRewardBlocksWindow) { ASSERT_EQ(blockchainExplorer.getRewardBlocksWindow(), parameters::QUID_REWARD_BLOCKS_WINDOW); } TEST_F(BlockchainExplorerTests, getRewardBlocksWindowNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.getRewardBlocksWindow()); } TEST_F(BlockchainExplorerTests, getFullRewardMaxBlockSize) { ASSERT_EQ(blockchainExplorer.getFullRewardMaxBlockSize(1), parameters::QUID_BLOCK_GRANTED_FULL_REWARD_ZONE); ASSERT_EQ(blockchainExplorer.getFullRewardMaxBlockSize(2), parameters::QUID_BLOCK_GRANTED_FULL_REWARD_ZONE); } TEST_F(BlockchainExplorerTests, getFullRewardMaxBlockSizeNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.getFullRewardMaxBlockSize(1)); } TEST_F(BlockchainExplorerTests, isSynchronizedFalse) { ASSERT_FALSE(blockchainExplorer.isSynchronized()); } TEST_F(BlockchainExplorerTests, isSynchronizedNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); ASSERT_ANY_THROW(newExplorer.isSynchronized()); } TEST_F(BlockchainExplorerTests, isSynchronizedNotification) { smartObserver observer; CallbackStatus status; std::function<void(const BlockDetails& topBlock)> cb = [&status, this](const BlockDetails& topBlock) { EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); status.setStatus(std::error_code()); }; observer.setCallback(cb); blockchainExplorer.addObserver(&observer); nodeStub.setSynchronizedStatus(true); ASSERT_TRUE(blockchainExplorer.isSynchronized()); ASSERT_TRUE(status.wait()); } TEST_F(BlockchainExplorerTests, blockchainUpdatedEmpty) { smartObserver observer; CallbackStatus status; std::function< void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) > cb = [&status, this](const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) { EXPECT_EQ(newBlocks.size(), 0); EXPECT_EQ(orphanedBlocks.size(), 0); status.setStatus(std::error_code()); }; observer.setCallback(cb); blockchainExplorer.addObserver(&observer); nodeStub.sendLocalBlockchainUpdated(); ASSERT_TRUE(status.wait()); } TEST_F(BlockchainExplorerTests, blockchainUpdatedMany) { const size_t NUMBER_OF_BLOCKS = 10; std::vector<Hash> blockHashes; generator.generateEmptyBlocks(NUMBER_OF_BLOCKS); ASSERT_GE(generator.getBlockchain().size(), NUMBER_OF_BLOCKS); for (auto iter = generator.getBlockchain().begin() + 2; iter != generator.getBlockchain().end(); iter++) { if (blockHashes.size() == NUMBER_OF_BLOCKS) { break; } Hash hash = get_block_hash(*iter); blockHashes.push_back(hash); } smartObserver observer; CallbackStatus status; std::function< void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) > cb = [&status, &blockHashes, this, NUMBER_OF_BLOCKS](const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) { EXPECT_EQ(newBlocks.size(), NUMBER_OF_BLOCKS); EXPECT_EQ(orphanedBlocks.size(), 0); auto range = boost::combine(blockHashes, newBlocks); for (const boost::tuple<Hash, BlockDetails>& hashWithBlock : range) { EXPECT_EQ(hashWithBlock.get<0>(), hashWithBlock.get<1>().hash); EXPECT_FALSE(hashWithBlock.get<1>().isOrphaned); } status.setStatus(std::error_code()); }; observer.setCallback(cb); blockchainExplorer.addObserver(&observer); nodeStub.sendLocalBlockchainUpdated(); ASSERT_TRUE(status.wait()); } TEST_F(BlockchainExplorerTests, poolUpdatedEmpty) { smartObserver observer; CallbackStatus status; std::function< void(const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) > cb = [&status, this](const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) { EXPECT_EQ(newTransactions.size(), 0); EXPECT_EQ(removedTransactions.size(), 0); status.setStatus(std::error_code()); }; observer.setCallback(cb); blockchainExplorer.addObserver(&observer); nodeStub.sendPoolChanged(); ASSERT_FALSE(status.wait()); } TEST_F(BlockchainExplorerTests, poolUpdatedMany) { size_t POOL_TX_NUMBER = 10; std::vector<Hash> poolTxs; for (size_t i = 0; i < POOL_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); poolTxs.push_back(hash); generator.putTxToPool(tx); } nodeStub.setSynchronizedStatus(true); { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); smartObserver observer; CallbackStatus status; std::function< void(const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) > cb = [&status, &poolTxs, this, POOL_TX_NUMBER](const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) { EXPECT_EQ(newTransactions.size(), POOL_TX_NUMBER); EXPECT_EQ(removedTransactions.size(), 0); for (const Hash& poolTxHash : poolTxs) { auto iter = std::find_if( newTransactions.begin(), newTransactions.end(), [&poolTxHash](const TransactionDetails& txDetails) -> bool { return poolTxHash == txDetails.hash; } ); EXPECT_NE(iter, newTransactions.end()); EXPECT_EQ(iter->hash, poolTxHash); EXPECT_FALSE(iter->inBlockchain); } status.setStatus(std::error_code()); }; observer.setCallback(cb); std::function< void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) > cb1 = [&status, this](const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) {}; observer.setCallback(cb1); nodeStub.sendLocalBlockchainUpdated(); blockchainExplorer.addObserver(&observer); nodeStub.sendPoolChanged(); ASSERT_TRUE(status.wait()); blockchainExplorer.removeObserver(&observer); } generator.putTxPoolToBlockchain(); { BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); smartObserver observer; CallbackStatus status; CallbackStatus status1; std::function< void(const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) > cb = [&status, &poolTxs, this, POOL_TX_NUMBER](const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) { EXPECT_EQ(newTransactions.size(), 0); EXPECT_EQ(removedTransactions.size(), POOL_TX_NUMBER); for (const Hash& poolTxHash : poolTxs) { auto iter = std::find_if( removedTransactions.begin(), removedTransactions.end(), [&poolTxHash](const std::pair<Hash, TransactionRemoveReason>& txDetails) -> bool { return poolTxHash == txDetails.first; } ); EXPECT_NE(iter, removedTransactions.end()); EXPECT_EQ(iter->first, poolTxHash); EXPECT_EQ(iter->second, TransactionRemoveReason::INCLUDED_IN_BLOCK); } status.setStatus(std::error_code()); }; observer.setCallback(cb); std::function< void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) > cb1 = [&status1, this](const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) { status1.setStatus(std::error_code()); }; observer.setCallback(cb1); blockchainExplorer.addObserver(&observer); nodeStub.sendLocalBlockchainUpdated(); ASSERT_TRUE(status1.wait()); nodeStub.sendPoolChanged(); ASSERT_TRUE(status.wait()); blockchainExplorer.removeObserver(&observer); } } TEST_F(BlockchainExplorerTests, poolUpdatedManyNotSynchronized) { size_t POOL_TX_NUMBER = 10; std::vector<Hash> poolTxs; for (size_t i = 0; i < POOL_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); poolTxs.push_back(hash); generator.putTxToPool(tx); } nodeStub.setSynchronizedStatus(false); BlockDetails topBlock; ASSERT_GE(generator.getBlockchain().size(), 1); ASSERT_TRUE(blockchainExplorer.getBlockchainTop(topBlock)); EXPECT_EQ(topBlock.height, generator.getBlockchain().size() - 1); EXPECT_FALSE(topBlock.isOrphaned); smartObserver observer; CallbackStatus status; std::function< void(const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) > cb = [&status, &poolTxs, this, POOL_TX_NUMBER](const std::vector<TransactionDetails>& newTransactions, const std::vector<std::pair<Hash, TransactionRemoveReason>>& removedTransactions) { EXPECT_EQ(newTransactions.size(), POOL_TX_NUMBER); EXPECT_EQ(removedTransactions.size(), 0); for (const Hash& poolTxHash : poolTxs) { auto iter = std::find_if( newTransactions.begin(), newTransactions.end(), [&poolTxHash](const TransactionDetails& txDetails) -> bool { return poolTxHash == txDetails.hash; } ); EXPECT_NE(iter, newTransactions.end()); EXPECT_EQ(iter->hash, poolTxHash); EXPECT_FALSE(iter->inBlockchain); } status.setStatus(std::error_code()); }; observer.setCallback(cb); std::function< void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) > cb1 = [&status, this](const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) {}; observer.setCallback(cb1); nodeStub.sendLocalBlockchainUpdated(); blockchainExplorer.addObserver(&observer); nodeStub.sendPoolChanged(); ASSERT_FALSE(status.wait()); blockchainExplorer.removeObserver(&observer); } TEST_F(BlockchainExplorerTests, unexpectedTermination) { smartObserver observer; std::function< void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) > cb = [this](const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) { EXPECT_EQ(newBlocks.size(), 0); EXPECT_EQ(orphanedBlocks.size(), 0); }; observer.setCallback(cb); blockchainExplorer.addObserver(&observer); for (uint8_t i = 0; i < 100; ++i) nodeStub.sendLocalBlockchainUpdated(); blockchainExplorer.removeObserver(&observer); } TEST_F(BlockchainExplorerTests, unexpectedExeption) { smartObserver observer; CallbackStatus status; std::function< void(const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) > cb = [&status, this](const std::vector<BlockDetails>& newBlocks, const std::vector<BlockDetails>& orphanedBlocks) { EXPECT_EQ(newBlocks.size(), 0); EXPECT_EQ(orphanedBlocks.size(), 0); status.setStatus(std::error_code()); throw std::system_error(std::error_code()); }; observer.setCallback(cb); blockchainExplorer.addObserver(&observer); nodeStub.sendLocalBlockchainUpdated(); ASSERT_TRUE(status.wait()); } TEST_F(BlockchainExplorerTests, getBlocksByTimestampGenesis) { ASSERT_GE(generator.getBlockchain().size(), 1); Hash genesisHash = get_block_hash(generator.getBlockchain().front()); std::vector<BlockDetails> blocks; uint32_t totalBlocksNumber; ASSERT_TRUE(blockchainExplorer.getBlocks(0, 0, 1, blocks, totalBlocksNumber)); ASSERT_EQ(blocks.size(), 1); EXPECT_EQ(totalBlocksNumber, 1); Hash expectedHash = genesisHash; EXPECT_EQ(blocks.front().hash, expectedHash); EXPECT_EQ(blocks.front().timestamp, 0); EXPECT_FALSE(blocks.front().isOrphaned); } TEST_F(BlockchainExplorerTests, getBlocksByTimestampMany) { const size_t NUMBER_OF_BLOCKS = 10; std::vector<Hash> blockHashes; uint64_t startTime = static_cast<uint64_t>(time(NULL) + currency.difficultyTarget() - 1); generator.generateEmptyBlocks(NUMBER_OF_BLOCKS); uint64_t endTime = startTime + currency.difficultyTarget() * NUMBER_OF_BLOCKS; ASSERT_EQ(generator.getBlockchain().size(), NUMBER_OF_BLOCKS + 2); for (auto iter = generator.getBlockchain().begin() + 2; iter != generator.getBlockchain().end(); iter++) { Hash hash = get_block_hash(*iter); blockHashes.push_back(hash); } std::vector<BlockDetails> blocks; uint32_t totalBlocksNumber; ASSERT_TRUE(blockchainExplorer.getBlocks(startTime, endTime, NUMBER_OF_BLOCKS, blocks, totalBlocksNumber)); EXPECT_EQ(blocks.size(), NUMBER_OF_BLOCKS); EXPECT_EQ(totalBlocksNumber, NUMBER_OF_BLOCKS); ASSERT_EQ(blockHashes.size(), blocks.size()); auto range = boost::combine(blockHashes, blocks); for (const boost::tuple<Hash, BlockDetails>& hashWithBlock : range) { EXPECT_EQ(hashWithBlock.get<0>(), hashWithBlock.get<1>().hash); EXPECT_FALSE(hashWithBlock.get<1>().isOrphaned); } } TEST_F(BlockchainExplorerTests, getBlocksByTimestampFail) { uint64_t startTime = currency.difficultyTarget() + 1; std::vector<BlockDetails> blocks; uint32_t totalBlocksNumber; EXPECT_EQ(generator.getBlockchain().size(), 2); ASSERT_ANY_THROW(blockchainExplorer.getBlocks(startTime, startTime + 5, 1, blocks, totalBlocksNumber)); } TEST_F(BlockchainExplorerTests, getBlocksByTimestampNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); uint64_t startTime = static_cast<uint64_t>(time(NULL)); std::vector<BlockDetails> blocks; uint32_t totalBlocksNumber; ASSERT_ANY_THROW(newExplorer.getBlocks(startTime, startTime, 1, blocks, totalBlocksNumber)); } TEST_F(BlockchainExplorerTests, generatedTransactions) { const size_t NUMBER_OF_BLOCKS = 10; const size_t POOL_TX_NUMBER = 10; std::vector<uint32_t> blockHeights; for (uint32_t i = 0; i < NUMBER_OF_BLOCKS + 3; ++i) { blockHeights.push_back(i); } for (size_t i = 0; i < POOL_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); generator.putTxToPool(tx); } std::vector<std::vector<BlockDetails>> blocks; generator.generateEmptyBlocks(NUMBER_OF_BLOCKS); generator.putTxPoolToBlockchain(); ASSERT_EQ(generator.getBlockchain().size(), NUMBER_OF_BLOCKS + 3); ASSERT_TRUE(blockchainExplorer.getBlocks(blockHeights, blocks)); EXPECT_EQ(blocks.size(), NUMBER_OF_BLOCKS + 3); ASSERT_EQ(blockHeights.size(), blocks.size()); auto range = boost::combine(blockHeights, blocks); for (const boost::tuple<size_t, std::vector<BlockDetails>>& sameHeight : range) { EXPECT_EQ(sameHeight.get<1>().size(), 1); for (const BlockDetails& block : sameHeight.get<1>()) { EXPECT_EQ(block.height, sameHeight.get<0>()); EXPECT_FALSE(block.isOrphaned); if (block.height != NUMBER_OF_BLOCKS + 2) { EXPECT_EQ(block.alreadyGeneratedTransactions, block.height + 1); } else { EXPECT_EQ(block.alreadyGeneratedTransactions, block.height + 1 + POOL_TX_NUMBER); } } } } TEST_F(BlockchainExplorerTests, getPoolTransactionsByTimestampEmpty) { ASSERT_GE(generator.getBlockchain().size(), 1); std::vector<TransactionDetails> transactions; uint64_t totalTransactionsNumber; ASSERT_TRUE(blockchainExplorer.getPoolTransactions(0, 0, 1, transactions, totalTransactionsNumber)); ASSERT_EQ(transactions.size(), 0); ASSERT_EQ(totalTransactionsNumber, 0); } TEST_F(BlockchainExplorerTests, getPoolTransactionsByTimestampMany) { uint32_t POOL_TX_NUMBER = 10; std::vector<Hash> poolTxs; for (uint32_t i = 0; i < POOL_TX_NUMBER; ++i) { auto txptr = createTransaction(); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); poolTxs.push_back(hash); generator.putTxToPool(tx); } std::vector<TransactionDetails> transactions; uint64_t totalTransactionsNumber; ASSERT_TRUE(blockchainExplorer.getPoolTransactions(0, 0, 1, transactions, totalTransactionsNumber)); ASSERT_EQ(transactions.size(), 1); ASSERT_EQ(totalTransactionsNumber, POOL_TX_NUMBER); transactions.clear(); ASSERT_TRUE(blockchainExplorer.getPoolTransactions(0, 0, POOL_TX_NUMBER, transactions, totalTransactionsNumber)); ASSERT_EQ(transactions.size(), POOL_TX_NUMBER); ASSERT_EQ(totalTransactionsNumber, POOL_TX_NUMBER); } TEST_F(BlockchainExplorerTests, getPoolTransactionsByTimestampFail) { uint64_t startTime = currency.difficultyTarget() + 1; std::vector<TransactionDetails> transactions; uint64_t totalTransactionsNumber; EXPECT_EQ(generator.getBlockchain().size(), 2); ASSERT_ANY_THROW(blockchainExplorer.getPoolTransactions(startTime, startTime + 5, 1, transactions, totalTransactionsNumber)); } TEST_F(BlockchainExplorerTests, getPoolTransactionsByTimestampNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); uint64_t startTime = static_cast<uint64_t>(time(NULL)); std::vector<TransactionDetails> transactions; uint64_t totalTransactionsNumber; ASSERT_ANY_THROW(newExplorer.getPoolTransactions(startTime, startTime, 1, transactions, totalTransactionsNumber)); } TEST_F(BlockchainExplorerTests, getTransactionsByPaymentId) { size_t PAYMENT_ID_NUMBER = 3; size_t TX_PER_PAYMENT_ID = 5; std::unordered_map<Hash, Hash> txs; std::vector<Hash> paymentIds; for (size_t i = 0; i < PAYMENT_ID_NUMBER; ++i) { Hash randomPaymentId; for (uint8_t& j : randomPaymentId.data) { j = rand(); } paymentIds.push_back(randomPaymentId); for (size_t j = 0; j < TX_PER_PAYMENT_ID; ++j) { auto txptr = createTransaction(); txptr->setPaymentId(randomPaymentId); auto tx = ::createTx(*txptr.get()); Hash hash = getObjectHash(tx); txs.emplace(hash, randomPaymentId); generator.addTxToBlockchain(tx); } } for (auto paymentId : paymentIds) { std::vector<TransactionDetails> transactions; ASSERT_TRUE(blockchainExplorer.getTransactionsByPaymentId(paymentId, transactions)); ASSERT_EQ(transactions.size(), TX_PER_PAYMENT_ID); for (auto transaction : transactions) { auto iter = txs.find(transaction.hash); ASSERT_NE(iter, txs.end()); EXPECT_EQ(iter->second, paymentId); EXPECT_EQ(iter->second, transaction.paymentId); } } } TEST_F(BlockchainExplorerTests, getTransactionsByPaymentIdFail) { std::vector<TransactionDetails> transactions; Hash randomPaymentId; for (uint8_t& i : randomPaymentId.data) { i = rand(); } EXPECT_EQ(generator.getBlockchain().size(), 2); ASSERT_ANY_THROW(blockchainExplorer.getTransactionsByPaymentId(randomPaymentId, transactions)); } TEST_F(BlockchainExplorerTests, getTransactionsByPaymentIdNotInited) { BlockchainExplorer newExplorer(nodeStub, logger); Hash randomPaymentId; for (uint8_t& i : randomPaymentId.data) { i = rand(); } std::vector<TransactionDetails> transactions; EXPECT_EQ(generator.getBlockchain().size(), 2); ASSERT_ANY_THROW(newExplorer.getTransactionsByPaymentId(randomPaymentId, transactions)); }
[ "cycereorg@gmail.com" ]
cycereorg@gmail.com
6b0511946e1a1aec189275ad37f95e5e2be2d7a0
ded7b6d79b14eee45f78ef4cd5418d4c59071dac
/machine.cpp
34603a91eb9f9448a3fd9375ffad5f1113571671
[]
no_license
shamkeev/godfather
2f25dc5aeba6d0198106abc81a437ef9b4ef3b89
39cbc504ca44754d393664bd4e28856fa50fa6bd
refs/heads/master
2021-03-12T21:28:45.612215
2013-03-15T16:07:16
2013-03-15T16:07:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
241
cpp
#include "machine.h" namespace vm { Machine::Machine() : memory(), pic(), cpu(memory, pic){} Machine::~Machine() {} void Machine::Start() { for(;;) { cpu.Step(); pic.irq_0(); //General the Timer Interrupt } } }
[ "shamkeyev@mail.ru" ]
shamkeyev@mail.ru
89daa23f4638ed857079cb356de527556406cc25
1d04a44976a0d0effd12b9f1bc18db7bc4c8f96d
/be/src/runtime/string-search-test.cc
a7804cc58f07a4fe433bbd1d779c5ce5eea7df34
[ "OpenSSL", "Apache-2.0", "BSD-3-Clause", "dtoa", "MIT", "PSF-2.0", "LicenseRef-scancode-mit-modification-obligations", "bzip2-1.0.6", "LicenseRef-scancode-unknown-license-reference", "Minpack", "BSL-1.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-openssl", ...
permissive
Pandinosaurus/Impala
d2d189e9efd93196d4fac36f91e926cca041f023
7dd2c8100f6d810bde13a0c9f8fb8449344cdcef
refs/heads/cdh5-trunk
2023-03-13T00:09:43.104849
2019-07-25T00:12:06
2019-08-14T21:51:53
149,855,108
1
0
Apache-2.0
2019-08-15T22:47:12
2018-09-22T07:24:05
C++
UTF-8
C++
false
false
5,371
cc
// 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. #include <gtest/gtest.h> #include "runtime/string-search.h" namespace impala { StringValue StrValFromCString(const char* str, int len) { if (len == -1) len = strlen(str); return StringValue(const_cast<char*>(str), len); } // Test string search for haystack/needle, up to len for each. // If the length is -1, use the full string length. // Searching in a substring allows checking whether the search respects the // length stored in the StringValue or also reads parts of the string which // should be excluded. int TestSearch(const char* haystack, const char* needle, int haystack_len = -1, int needle_len = -1) { StringValue needle_str_val = StrValFromCString(needle, needle_len); StringValue haystack_str_val = StrValFromCString(haystack, haystack_len); StringSearch search(&needle_str_val); return search.Search(&haystack_str_val); } // Test reverse string search for haystack/needle, up to len for each. // If the length is -1, use the full string length. // Searching in a substring allows checking whether the search respects the // length stored in the StringValue or also reads parts of the string which // should be excluded. int TestRSearch(const char* haystack, const char* needle, int haystack_len = -1, int needle_len = -1) { StringValue needle_str_val = StrValFromCString(needle, needle_len); StringValue haystack_str_val = StrValFromCString(haystack, haystack_len); StringSearch search(&needle_str_val); return search.RSearch(&haystack_str_val); } TEST(StringSearchTest, RegularSearch) { // Basic Tests EXPECT_EQ(0, TestSearch("abcdabcd", "a")); EXPECT_EQ(0, TestSearch("abcdabcd", "ab")); EXPECT_EQ(2, TestSearch("abcdabcd", "c")); EXPECT_EQ(2, TestSearch("abcdabcd", "cd")); EXPECT_EQ(-1, TestSearch("", "")); EXPECT_EQ(-1, TestSearch("abc", "")); EXPECT_EQ(-1, TestSearch("", "a")); // Test single chars EXPECT_EQ(0, TestSearch("a", "a")); EXPECT_EQ(-1, TestSearch("a", "b")); EXPECT_EQ(1, TestSearch("abc", "b")); // Test searching in a substring of the haystack EXPECT_EQ(0, TestSearch("abcabcd", "abc", 5)); EXPECT_EQ(-1, TestSearch("abcabcd", "abcd", 5)); EXPECT_EQ(-1, TestSearch("abcabcd", "abcd", 0)); // Test searching a substring of the needle in a substring of the haystack. EXPECT_EQ(0, TestSearch("abcde", "abaaaaaa", 4, 2)); EXPECT_EQ(-1, TestSearch("abcde", "abaaaaaa", 4, 3)); EXPECT_EQ(-1, TestSearch("abcdabaaaaa", "abaaaaaa", 4, 3)); EXPECT_EQ(-1, TestSearch("abcdabaaaaa", "abaaaaaa", 4, 0)); EXPECT_EQ(-1, TestSearch("abcdabaaaaa", "abaaaaaa")); // Test with needle matching the end of the substring. EXPECT_EQ(4, TestSearch("abcde", "e")); EXPECT_EQ(3, TestSearch("abcde", "de")); EXPECT_EQ(2, TestSearch("abcdede", "cde")); EXPECT_EQ(5, TestSearch("abcdacde", "cde")); // Test correct skip_ handling, which depends on which char of the needle is // the same as the last one. EXPECT_EQ(2, TestSearch("ababcacac", "abcacac")); } TEST(StringSearchTest, ReverseSearch) { // Basic Tests EXPECT_EQ(4, TestRSearch("abcdabcd", "a")); EXPECT_EQ(4, TestRSearch("abcdabcd", "ab")); EXPECT_EQ(6, TestRSearch("abcdabcd", "c")); EXPECT_EQ(6, TestRSearch("abcdabcd", "cd")); EXPECT_EQ(-1, TestRSearch("", "")); EXPECT_EQ(-1, TestRSearch("abc", "")); EXPECT_EQ(-1, TestRSearch("", "a")); // Test single chars EXPECT_EQ(0, TestRSearch("a", "a")); EXPECT_EQ(-1, TestRSearch("a", "b")); EXPECT_EQ(1, TestRSearch("abc", "b")); // Test searching in a substring of the haystack EXPECT_EQ(0, TestRSearch("abcabcd", "abc", 5)); EXPECT_EQ(-1, TestRSearch("abcabcd", "abcd", 5)); EXPECT_EQ(-1, TestRSearch("abcabcd", "abcd", 0)); // Test searching a substring of the needle in a substring of the haystack. EXPECT_EQ(0, TestRSearch("abcde", "abaaaaaa", 4, 2)); EXPECT_EQ(-1, TestRSearch("abcde", "abaaaaaa", 4, 3)); EXPECT_EQ(-1, TestRSearch("abcdabaaaaa", "abaaaaaa", 4, 3)); EXPECT_EQ(-1, TestRSearch("abcdabaaaaa", "abaaaaaa", 4, 0)); EXPECT_EQ(-1, TestRSearch("abcdabaaaaa", "abaaaaaa")); // Test with needle matching the end of the substring. EXPECT_EQ(4, TestRSearch("abcde", "e")); EXPECT_EQ(3, TestRSearch("abcde", "de")); EXPECT_EQ(2, TestRSearch("abcdede", "cde")); EXPECT_EQ(5, TestRSearch("abcdacde", "cde")); // Test correct rskip_ handling, which depends on which char of the needle is // the same as the first one. EXPECT_EQ(0, TestRSearch("cacacbaba", "cacacba")); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "aphadke@cloudera.com" ]
aphadke@cloudera.com
09099025499e98b86f41e19baa7fecfdad387d7f
eaae3bc291b9b8455e3f56650271655089fff997
/EFE Engine/sources/resources/MeshLoaderHandler.cpp
22734a52282127bee9bb917d35ab7293b752774f
[]
no_license
mifozski/EFE-Engine
59b6274830b68fa2e7f21b5d91de9d222297cbcb
32521a8f534e3ff863617bfb42360f8f568bacd0
refs/heads/master
2021-05-28T07:35:55.934515
2015-01-02T20:08:55
2015-01-02T20:08:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,135
cpp
#include "resources/MeshLoaderHandler.h" #include "resources/MeshLoader.h" #include "system/String.h" #include "system/LowLevelSystem.h" #include "resources/Resources.h" #include "scene/Scene.h" namespace efe { bool iMeshLoader::m_bRestricStaticLightToSector = false; bool iMeshLoader::m_bUseFastMaterial = false; tString iMeshLoader::m_sFastMaterialFile = ""; tString iMeshLoader::m_sCacheDir = "core/cache"; cMeshLoaderHandler::cMeshLoaderHandler(cResources *a_pResources, cScene *a_pScene) { m_pResources = a_pResources; m_pScene = a_pScene; } cMeshLoaderHandler::~cMeshLoaderHandler() { tMeshLoaderListIt it = m_lstLoaders.begin(); for (;it != m_lstLoaders.end(); it++) efeDelete(*it); m_lstLoaders.clear(); } cMesh *cMeshLoaderHandler::LoadMesh(const tString &a_sFile, tMeshLoadFlag a_tFlags) { tString sType = cString::ToLowerCase(cString::GetFileExt(a_sFile)); tMeshLoaderListIt it = m_lstLoaders.begin(); for (;it != m_lstLoaders.end(); it++) { iMeshLoader *pLoader = *it; if (pLoader->IsSupported(sType)) return pLoader->LoadMesh(a_sFile, a_tFlags); } Log("No loader for '%s' found!\n", sType.c_str()); return NULL; } bool cMeshLoaderHandler::SaveMesh(cMesh *a_pMesh, const tString &a_sFile) { tString sType = cString::ToLowerCase(cString::GetFileExt(a_sFile)); tMeshLoaderListIt it = m_lstLoaders.begin(); for (;it != m_lstLoaders.end();++it) { iMeshLoader *pLoader = *it; if (pLoader->IsSupported(sType)) return pLoader->SaveMesh(a_pMesh,a_sFile); } Log("No loader for '%s' found!\n",sType.c_str()); return false; } //cWorld3D *cMeshLoaderHandler::LoadWorld(const tString &a_sFile, cScene *a_pScene, tWorldLoadFlag a_Flags) //{ //} void cMeshLoaderHandler::AddLoader(iMeshLoader *a_pLoader) { m_lstLoaders.push_back(a_pLoader); a_pLoader->m_pMaterialManager = m_pResources->GetMaterialManager(); a_pLoader->m_pMeshManager = m_pResources->GetMeshManager(); a_pLoader->m_pAnimationManager = m_pResources->GetAnimationManager(); //a_pLoader->m_pSystem = m_pScene- a_pLoader->AddSupportedTypes(&m_vSupportedTypes); } }
[ "efa34@yahoo.com" ]
efa34@yahoo.com
c9ddd198a653d17cff923e69e320c87544d48dc0
faacd0003e0c749daea18398b064e16363ea8340
/modules/default_home/default_home.h
6c8fe015e856157267065e562389d7d7250054ca
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
2,406
h
/* * Copyright (C) 2008 Pavlov Denis * * Default main home module. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or any later version. * */ #ifndef __DEFAULT_HOME_H__ #define __DEFAULT_HOME_H__ #include <QtGui> #include <QtXml> #include <QPushButton> #include "panel.h" #include "buttons.h" #include "skinner.h" #include "animated.h" #include "m_interface.h" class homeModuleWidget : public QWidget { Q_OBJECT public: /* public members */ homeModuleWidget(QWidget * parent = 0, ASkinner *s = 0); ~homeModuleWidget(); void setSkinner(ASkinner *s) { m_skinner = s; } void animateReverse(); private: /* private members */ ASkinner * m_skinner; ALyxAnimation *lastAnimation; // Buttons and animations in hashes with "button name" key. QHash<QString, ALyxAnimation *> animations; QHash<QString, ALyxButton *> buttons; private slots: void activateModule(); signals: void activateClicked(QString); void animationFinished(); }; class homeModuleApplet : public QWidget { Q_OBJECT public: /* public members */ homeModuleApplet(QWidget * parent = 0, ASkinner *s = 0); ~homeModuleApplet(); void setSkinner(ASkinner *s) { m_skinner = s; } private: /* private members */ ASkinner * m_skinner; private slots: signals: void buttonClicked(); }; class homeModule : public QObject, M_Interface { Q_OBJECT Q_INTERFACES(M_Interface) public: QWidget * activate(QWidget * parent = 0); QWidget * activateApplet(QWidget * parent = 0); void deactivate(QString deactivateFor); private: homeModuleApplet * appletWidget; homeModuleWidget * moduleWidget; QString nextModuleName; private slots: void deactivationFinished(); signals: void demandActivation(QString moduleName); void deactivated(QString deactivateFor); public slots: //! \brief Module activation slot - creates and shows main module widget void activateMyself() { // Module emits signal demanding an activation. emit demandActivation(m_moduleName); } //! \brief Module activation slot - creates and shows main module <mname> widget void activateModuleWidget(QString mname) { // Module emits signal demanding an activation. emit demandActivation(mname); } }; #endif
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9
13f59f8bf9d86f7db75502f61a8bd3c9abebe38e
066e8c5ec1f9f1794cdecf15113b22bcb2e8979a
/src/sim_log.cpp
769e735185812c7adf527425c9bea78049b81b0d
[]
no_license
DXD0706/simulator
64a9a4ee18257f045cac2e18d6fc677643f83909
27d05c95e9ab13dc8f4c09d25306cde857d354b1
refs/heads/master
2021-08-16T19:20:07.239850
2017-11-20T07:57:33
2017-11-20T07:57:33
94,093,625
1
2
null
null
null
null
UTF-8
C++
false
false
5,244
cpp
#include <sys/stat.h> #include <string.h> #include <strings.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <dirent.h> #include "sim_log.h" #include "sim_para.h" FILE *fp_log = NULL; FILE *fp_net = NULL; FILE *fp_poi = NULL; FILE *fp_ana = NULL; const char *SYS_PATH = "."; const char *APP_LOG_PATH = "log"; const char *APP_MSG_PATH = "msg"; const char *APP_SEC_PATH = "."; int g_sec_dev_init = 0; int create_dir(const char *dir_path) { int ret = 0; char path[200],path_t[200]; char *ptr_start,*ptr_end; bzero(path,sizeof(path)); strncpy(path,dir_path,strlen(dir_path)); ptr_start = &path[0]; ptr_end = &path[0]; ret = mkdir(path,S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH); if(ret == 0) { printf("Succes to Create %s\n",path); return 0; } else { if(errno == EEXIST) { /* File exists */ return 0; } else if(errno == ENOENT) { /* No such file or directory */ } else { return -1; } } while(*ptr_end++ != '\0') { if(ptr_end == &path[strlen(path)-1]) { ret = mkdir(path,S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH); if(ret == 0) { printf("Succes to Create %s\n",path); return 0; } else { return -1; } } if(*ptr_end == '/') { bzero(path_t,sizeof(path_t)); strncpy(path_t,path,ptr_end-ptr_start); ret = mkdir(path_t,S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH); if(ret == 0) { continue; } else { if(errno == EEXIST) { /* File exists */ continue; } else if(errno == EACCES) { /* Permission denied */ printf("%s\n",path_t); perror("mkdir "); return -1; } else { return -1; } } } } return 0; } int split_time(int *year,int *month,int *mday) { struct tm tm_now; time_t time_now = time(NULL); localtime_r(&time_now,&tm_now); *year = tm_now.tm_year+1900; *month = tm_now.tm_mon +1; *mday = tm_now.tm_mday; return 0; } FILE* create_log_file(char *dir,char *file,int year,int month,int mday) { char filename[256]; struct stat fstat; char o_mode[16] = "a+"; time_t time_now = time(NULL); memset(&fstat,0x00,sizeof(fstat)); memset(filename,0x00,sizeof(filename)); create_dir(dir); sprintf(filename,"%s/%d-%02d-%02d_%s",dir,year,month,mday,file); int ret = stat(filename,&fstat); if(ret != -1) { struct tm tm_file = *localtime(&fstat.st_ctime); int mday_file = tm_file.tm_mday; if(mday != mday_file) sprintf(o_mode,"w+"); else sprintf(o_mode,"a+"); } FILE *fp = fopen(filename,o_mode); if(fp == NULL) { printf("cannot open %s , %s\n",filename,strerror(errno)); return NULL; } setbuf(fp,NULL); fprintf(fp,"\t\t process start : %s",ctime(&time_now)); return fp; } int init_log() { int year = 0; int month = 0; int day = 0; char dir_path[255]; memset(dir_path,0x00,sizeof(dir_path)); sprintf(dir_path,"%s/%s",SYS_PATH,APP_LOG_PATH); split_time(&year,&month,&day); fp_log = create_log_file(dir_path,"sim_iec104.log",year,month,day); fp_net = create_log_file(dir_path,"sim_iec104.net",year,month,day); fp_poi = create_log_file(dir_path,"sim_iec104.poi",year,month,day); fp_ana = create_log_file(dir_path,"sim_iec104.ana",year,month,day); if (fp_log == NULL || fp_net == NULL) { printf("init log failed\n"); exit(1); } return 0; } int init_msg_log() { char dir_path[255]; char filename[256]; link_info_t *p_buf = NULL; memset(dir_path,0x00,sizeof(dir_path)); sprintf(dir_path,"%s/%s",SYS_PATH,APP_MSG_PATH); for_each_link(g_linkMap) { p_buf = it->second; sprintf(filename,"msg/%d.log",p_buf->linkno); p_buf->fp_msg= fopen(filename,"a+"); if (p_buf->fp_msg == NULL) { perror(filename); } } return 0; } int log_write_hex(FILE *fp,int direction,unsigned char *buf,size_t len) { char str[1024]; if (fp == NULL || buf == NULL) { return -1; } time_t time_now = time(NULL); memset(str,0x00,sizeof(str)); if (direction == DIR_RECV) { sprintf(str,"RECV %s",ctime(&time_now)); } else { sprintf(str,"SEND %s",ctime(&time_now)); } char *p = &str[strlen(str)]; for (size_t i=0; i<len; i++) { sprintf(p,"%02x ",buf[i]); p+=3; } sprintf(p,"\n"); fprintf(fp,"%s",str); fflush(fp); return 0; } int log_write_hex(link_info_t *plink_info,int direction,unsigned char *buf,size_t len) { if (plink_info == NULL || buf == NULL) { return -1; } if (plink_info->linkno > 100) { return 0; } return log_write_hex(plink_info->fp_msg, direction, buf, len); }
[ "dxd0706@gmail.com" ]
dxd0706@gmail.com
43633b8cb1cceefced574aed24823ca4bac3c723
6e8681a0d9195923130f6aaaec592086e9a784f9
/Trunk/2017_fall/Resources/CppBook-SourceCode/Chap11/cmdlineargs.cpp
4958515a3db872ca53231ae6064b1fb9071ae10f
[]
no_license
rugbyprof/1063-Data-Structures
a7faa4b855f3ae18f62c654703234e786d5d7f68
e41697c60e2ad113105634348d5211c454bcd900
refs/heads/master
2021-10-23T02:25:32.756031
2021-10-15T16:22:23
2021-10-15T16:22:23
17,293,996
24
42
null
2019-10-01T16:23:48
2014-02-28T17:30:57
C++
UTF-8
C++
false
false
146
cpp
#include <iostream> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) std::cout << '[' << argv[i] << "]\n"; }
[ "griffin@Terrys-MBP.att.net" ]
griffin@Terrys-MBP.att.net
d1ecf41d3edc8bc95c13ce0249e5a4e2539bf9ce
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/FileNameParser.h
668210e2dca720fdae0415faefcbe80ad94aa658
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
2,018
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ class FileNameParser { public: FileNameParser(); FileNameParser(LPCTSTR fileName); BOOL ParseFileName(LPCTSTR fileName, LPCTSTR pattern = NULL); LPCTSTR GetArtist() {return m_Artist;} LPCTSTR GetAlbum() {return m_Album;} INT GetTrackNo() {return m_TrackNo;} LPCTSTR GetTitle() {return m_Title;} INT GetYear() {return m_Year;} static BOOL TranslatePattern(LPTSTR newName, UINT bfLen, LPCTSTR pattern, LPCTSTR artist, LPCTSTR album, LPCTSTR trackNo, LPCTSTR title, LPCTSTR year, LPCTSTR discard); static LPCTSTR GetReadPredefinedFormat(INT idx); static LPCTSTR GetWritePredefinedFormat(INT idx); #ifdef _UNITTESTING static BOOL UnitTest(); #endif private: const static int MAX_STRING = 100; TCHAR m_Artist[MAX_STRING]; TCHAR m_Album[MAX_STRING]; TCHAR m_Title[MAX_STRING]; INT m_TrackNo; INT m_Year; BOOL DecodeAs(LPCTSTR fileName, LPCTSTR pattern); //BOOL ExtractAttribute(TCHAR code, LPCTSTR startChar); INT ExtractAttribute(TCHAR code, TCHAR divider, LPCTSTR startChar); BOOL IsInteger(LPCTSTR str); };
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678
727387c50898430584539bc1e1b5133eedbaef89
c62611d69408397e3326464390e28a0e0ee84ad7
/moc/ast.cc
9d4294293d0f977cc0df51a85903359f8e21038d
[]
no_license
marcellfischbach/CobaltSKY
80f5c202c5387f9e450510f31c245226e9d9eb65
a4e8c1d59285276ca2a0b42009ef15518355578e
refs/heads/master
2021-01-10T20:59:20.920563
2019-05-23T14:53:11
2019-05-23T14:53:11
94,755,831
0
0
null
null
null
null
UTF-8
C++
false
false
13,783
cc
#include <ast.hh> #include <algorithm> namespace cs::moc { ASTNode::ASTNode(ASTNodeType type) : m_type(type) , m_parent(nullptr) { } ASTNodeType ASTNode::GetType() const { return m_type; } ASTNode* ASTNode::FindChildNode(ASTNodeType type) { for (auto child : m_children) { if (child->GetType() == type) { return child; } } return nullptr; } ASTNode* ASTNode::FindParentNode(ASTNodeType type) { ASTNode* testNode = this; while (testNode) { if (testNode->GetType() == type) { return testNode; } testNode = testNode->GetParent(); } return nullptr; } ASTNode* ASTNode::FindPrevSibling(ASTNodeType type) { if (!m_parent) { return nullptr; } std::vector<ASTNode*>::iterator it = std::find(m_parent->m_children.begin(), m_parent->m_children.end(), this); if (it != m_parent->m_children.begin()) { --it; for (;; it--) { if ((*it)->GetType() == type) { return *it; } if (it == m_parent->m_children.begin()) { break; } } } return nullptr; } ASTNode* ASTNode::FindNextSibling(ASTNodeType type) { if (!m_parent) { return nullptr; } std::vector<ASTNode*>::iterator it = std::find(m_parent->m_children.begin(), m_parent->m_children.end(), this); if (it != m_parent->m_children.end()) { for (++it; it != m_parent->m_children.end(); it++) { if ((*it)->GetType() == type) { return *it; } } } return nullptr; } ASTNode* ASTNode::FindPrevSibling() { if (!m_parent) { return nullptr; } std::vector<ASTNode*>::iterator it = std::find(m_parent->m_children.begin(), m_parent->m_children.end(), this); if (it == m_parent->m_children.end() || it == m_parent->m_children.begin()) { return nullptr; } it--; return *it; } ASTNode* ASTNode::FindNextSibling() { if (!m_parent) { return nullptr; } std::vector<ASTNode*>::iterator it = std::find(m_parent->m_children.begin(), m_parent->m_children.end(), this); if (it == m_parent->m_children.end()) { return nullptr; } it++; if (it == m_parent->m_children.end()) { return nullptr; } return *it; } void ASTNode::Add(ASTNode* node) { if (node) { m_children.push_back(node); node->m_parent = this; } } ASTNode* ASTNode::GetParent() { return m_parent; } const ASTNode* ASTNode::GetParent() const { return m_parent; } const std::vector<ASTNode*>& ASTNode::GetChildren() const { return m_children; } void ASTNode::DebugNode(int ind) { for (int i = 0; i < ind; ++i) { printf(" "); } Debug(); printf("\n"); for (auto child : m_children) { child->DebugNode(ind + 1); } } BlockNode::BlockNode() : ASTNode(eANT_Block) { } void BlockNode::Debug() { printf("BLCK"); } NamespaceNode::NamespaceNode() : ASTNode(eANT_Namespace) { } void NamespaceNode::SetName(const std::string & name) { m_name = name; } const std::string& NamespaceNode::GetName() const { return m_name; } void NamespaceNode::SetAlias(const std::string & alias) { m_alias = alias; } const std::string& NamespaceNode::GetAlias() const { return m_alias; } void NamespaceNode::Debug() { if (m_alias.empty()) { printf("NS[%s]", m_name.c_str()); } else { printf("NS[%s=%s]", m_alias.c_str(), m_name.c_str()); } } ClassSuperDefinition::ClassSuperDefinition(bool csSuper, const TypeDef & type, const std::string & visibility, bool virtuality) : m_csSuper(csSuper) , m_type(type) , m_visibility(visibility) , m_virtual(virtuality) { } bool ClassSuperDefinition::IsCSSuper() const { return m_csSuper; } const TypeDef& ClassSuperDefinition::GetType() const { return m_type; } const std::string& ClassSuperDefinition::GetVisibility() const { return m_visibility; } bool ClassSuperDefinition::IsVirtual() const { return m_virtual; } CSMetaNode::CSMetaNode(CSMetaNode::MetaType type) : ASTNode(eANT_CSMeta) , m_type(type) { } void CSMetaNode::Add(const CSMetaNode::Attribute & attribute) { m_attributes.push_back(attribute); } bool CSMetaNode::Has(const std::string& key) const { for (auto attribute : m_attributes) { if (attribute.key == key) { return true; } } return false; } std::string CSMetaNode::Get(const std::string& key) const { for (auto attribute : m_attributes) { if (attribute.key == key) { return attribute.value; } } return ""; } void CSMetaNode::Debug() { switch (m_type) { case eMT_Class: printf("CS_CLASS("); break; case eMT_Property: printf("CS_PROPERTY("); break; case eMT_Function: printf("CS_FUNCTION("); break; } for (auto attribute : m_attributes) { printf("["); if (!attribute.key.empty()) { printf("%s=", attribute.key.c_str()); } printf("%s]", attribute.value.c_str()); } printf(")"); } ClassNode::ClassNode() : ASTNode(eANT_Class) , m_struct(false) { } void ClassNode::SetStruct(bool strct) { m_struct = strct; } bool ClassNode::IsStruct() const { return m_struct; } void ClassNode::SetName(const std::string & name) { m_name = name; } const std::string& ClassNode::GetName() const { return m_name; } void ClassNode::AddSuper(const ClassSuperDefinition & super) { m_supers.push_back(super); } const std::vector<ClassSuperDefinition>& ClassNode::GetSupers() const { return m_supers; } bool ClassNode::HasPureVirtualMethod() { BlockNode* blockNode = static_cast<BlockNode*>(FindChildNode(eANT_Block)); if (!blockNode) { return false; } FunctionNode* functionNode = static_cast<FunctionNode*>(blockNode->FindChildNode(eANT_Function)); while (functionNode) { if (functionNode->IsVirtual() && functionNode->IsPureVirtual()) { return true; } functionNode = static_cast<FunctionNode*>(functionNode->FindNextSibling(eANT_Function)); } return false; } bool ClassNode::HasPublicDefaultConstructor() { BlockNode* blockNode = static_cast<BlockNode*>(FindChildNode(eANT_Block)); if (!blockNode) { return false; } bool hasConstructor = false; FunctionNode* functionNode = static_cast<FunctionNode*>(blockNode->FindChildNode(eANT_Function)); while (functionNode) { if (!functionNode->GetReturnValue().IsValid() && functionNode->GetName() == GetName()) { hasConstructor = true; VisibilityNode* visNode = static_cast<VisibilityNode*>(functionNode->FindPrevSibling(eANT_Visibility)); if (visNode == nullptr && m_struct || visNode != nullptr && visNode->GetVisibility() == "public") { // this is a constructor .. but is it a default constructor??? bool hasParameter = false; for (auto argument : functionNode->GetArguments()) { if (!argument.HasDefaultValue()) { hasParameter = true; break; } } if (!hasParameter) { return true; } } } functionNode = static_cast<FunctionNode*>(functionNode->FindNextSibling(eANT_Function)); } return !hasConstructor; } void ClassNode::Debug() { printf("%s[%s", m_struct ? "STRCT" : "CLS", m_name.c_str()); for (auto super : m_supers) { if (super.IsCSSuper()) { printf(" CS_SUPER(%s%s%s)", super.IsVirtual() ? "virtual " : "", super.GetVisibility().empty() ? "" : (super.GetVisibility() + " ").c_str(), super.GetType().GetText().c_str()); } else { printf(" native(%s%s%s)", super.IsVirtual() ? "virtual " : "", super.GetVisibility().empty() ? "" : (super.GetVisibility() + " ").c_str(), super.GetType().GetText().c_str() ); } } printf("]"); } VisibilityNode::VisibilityNode(const std::string & visibility) : ASTNode(eANT_Visibility) , m_visibility(visibility) { } const std::string& VisibilityNode::GetVisibility() const { return m_visibility; } void VisibilityNode::Debug() { printf("VSBLT[%s]", m_visibility.c_str()); } Argument::Argument(const TypeDef & type, const std::string & name, bool defaultValue) : m_type(type) , m_name(name) , m_defaultValue(defaultValue) { } const TypeDef& Argument::GetType() const { return m_type; } const std::string& Argument::GetName() const { return m_name; } bool Argument::HasDefaultValue() const { return m_defaultValue; } std::string Argument::GetText() const { std::string text = m_type.GetText(); if (!m_name.empty()) { text += " " + m_name; } return text; } FunctionNode::FunctionNode() : ASTNode(eANT_Function) , m_name("") , m_virtual(false) , m_pureVirtual(false) , m_const(false) { } void FunctionNode::SetName(const std::string & name) { m_name = name; } const std::string& FunctionNode::GetName() const { return m_name; } void FunctionNode::SetReturnValue(const TypeDef & returnValue) { m_returnValue = returnValue; } const TypeDef& FunctionNode::GetReturnValue() const { return m_returnValue; } void FunctionNode::SetVirtual(bool virtuality) { m_virtual = virtuality; } bool FunctionNode::IsVirtual() const { return m_virtual; } void FunctionNode::SetPureVirtual(bool pureVirtual) { m_pureVirtual = pureVirtual; } bool FunctionNode::IsPureVirtual() const { return m_pureVirtual; } void FunctionNode::SetConst(bool constness) { m_const = constness; } bool FunctionNode::IsConst() const { return m_const; } void FunctionNode::Add(const Argument & argument) { m_arguments.push_back(argument); } const std::vector<Argument>& FunctionNode::GetArguments() const { return m_arguments; } void FunctionNode::Debug() { std::string arguments = ""; for (size_t i = 0, in = m_arguments.size(); i < in; ++i) { arguments += m_arguments[i].GetText(); if (i + 1 < m_arguments.size()) { arguments += ", "; } } printf("FNCTN[%s%s%s%s(%s)]: %s", m_virtual ? "VIRTUAL " : "", m_name.c_str(), m_const ? " CONST" : "", m_pureVirtual ? " PURE " : "", arguments.c_str(), m_returnValue.GetText().c_str()); } MemberNode::MemberNode() : ASTNode(eANT_Member) { } void MemberNode::SetName(const std::string & name) { m_name = name; } const std::string& MemberNode::GetName() const { return m_name; } void MemberNode::SetType(const TypeDef & type) { m_type = type; } const TypeDef& MemberNode::GetType() const { return m_type; } void MemberNode::Debug() { printf("MMBR [%s:%s]", m_name.c_str(), m_type.GetText().c_str()); } TypeDef::TypeDef() : m_const(false) , m_constPtr(false) { } void TypeDef::Add(const Token & token) { switch (token.GetType()) { case eTT_Const: if (m_mems.empty()) { m_const = true; } else { m_constPtr = true; } break; case eTT_Ampersand: case eTT_Asterisk: case eTT_DoubleAsterisk: m_mems.push_back(token); break; default: m_tokens.push_back(token); break; } } void TypeDef::Add(const TypeDef & subType) { m_subTypes.push_back(subType); } void TypeDef::AddFront(const Token & token) { switch (token.GetType()) { case eTT_Const: m_const = true; break; case eTT_Ampersand: case eTT_Asterisk: case eTT_DoubleAsterisk: m_constPtr = m_constPtr || m_const; m_const = false; m_mems.insert(m_mems.begin(), token); break; default: m_tokens.insert(m_tokens.begin(), token); } } void TypeDef::AddFront(const TypeDef & subType) { m_subTypes.insert(m_subTypes.begin(), subType); } void TypeDef::SetConst(bool constness) { m_const = constness; } bool TypeDef::IsConst() const { return m_const; } bool TypeDef::IsValue() const { return this->m_mems.size() == 0; } bool TypeDef::IsReference() const { for (auto mem : m_mems) { if (mem.GetType() == eTT_Ampersand) { return true; } } return false; } bool TypeDef::IsPointer() const { for (auto mem : m_mems) { if (mem.GetType() == eTT_Asterisk) { return true; } } return false; } bool TypeDef::IsPointerToPointer() const { for (auto mem : m_mems) { if (mem.GetType() == eTT_DoubleAsterisk) { return true; } } return false; } bool TypeDef::IsVoid() const { return GetTypeName() == "void"; } bool TypeDef::IsValid() const { return !m_tokens.empty(); } const std::vector<TypeDef>& TypeDef::GetSubTypes() const { return m_subTypes; } std::string TypeDef::GetTypeName(bool withSubTypes) const { std::string typeName; for (auto tkn : m_tokens) { typeName += tkn.Get(); } if (!m_subTypes.empty() && withSubTypes) { typeName += "<"; for (size_t i = 0, in = m_subTypes.size(); i < in; ++i) { typeName += m_subTypes[i].GetText(); if (i + 1 < in) { typeName += ", "; } } typeName += ">"; } return typeName; } std::string TypeDef::GetText() const { std::string text; if (m_const) { text += "const "; } for (auto tkn : m_tokens) { text += tkn.Get(); } if (!m_subTypes.empty()) { text += "<"; for (size_t i = 0, in = m_subTypes.size(); i < in; ++i) { text += m_subTypes[i].GetText(); if (i + 1 < in) { text += ", "; } } text += ">"; } for (auto tkn : m_mems) { text += tkn.Get(); } if (m_constPtr) { text += " const"; } return text; } TokenNode::TokenNode() : ASTNode(eANT_Token) { } TokenNode::TokenNode(const Token & token) : ASTNode(eANT_Token) , m_token(token) { } void TokenNode::SetToken(const Token & token) { m_token = token; } const Token& TokenNode::GetToken() const { return m_token; } void TokenNode::Debug() { printf("TKN[%s]", m_token.Get().c_str()); } }
[ "marcell.fischbach@amova.eu" ]
marcell.fischbach@amova.eu
4cbf5a1ffc1a028636cc7154e54dd8f64efeb583
d5b6d9a9263cef8111e8835e92763b8922bb3155
/chapter.06/MyLib.02.h
588a95ee66e5492f887d746c9df08059eee27e5b
[]
no_license
goodpaperman/guide
df01b7271535c5906a54b95f3fd1a26b9647ba2b
40fecd13a40b1c3327e2a630b03a8de8ff57762e
refs/heads/master
2020-05-30T11:01:14.247642
2019-06-01T03:49:17
2019-06-01T03:49:17
189,687,421
0
0
null
null
null
null
UTF-8
C++
false
false
40
h
namespace MyLib { int a; int c; }
[ "haihai107@126.com" ]
haihai107@126.com
a491afe949d588b9f1e48c74cd67fb516461ae9a
9e4cc0c5deacf467141b8bbbf9931cdf9c62786c
/CaptureServer/src/CaptureStreamServerNew/Log.h
0f79c37ccef77381ba5b0b3fb703fddb1e3854b9
[]
no_license
XTJ21/CloudGamePlatform
57ab4cca09526af57a06130fe7e583b470c8361f
341d2d46cd7688fdb093be6b877bb02e1a89d058
refs/heads/master
2022-12-02T16:03:02.408027
2020-08-16T08:48:03
2020-08-16T08:48:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
126
h
#pragma once #include <string> using std::string; #define ALARM_SERVER_LOG "CaputureServer" int LogInit(string strUnitId);
[ "huqibin@linhansoft.com" ]
huqibin@linhansoft.com
d50b9d0f2870ae195a6643804a6c2ecdbfcdbbbd
975142ac6ec86cebb53de5e6e070fd8596379eaa
/MyFPSCamera.h
c2d7fe2c0b1d60c3ab09255ed53c03aaaa79fa3b
[]
no_license
ivandro/Nightmare-s-lair
9d66527c56a62c045a1ad2d64451ef2bdc37ea71
33a474be5ef5f476a29a7487fad0e4ed07be48cb
refs/heads/master
2016-09-06T07:00:29.032471
2011-12-05T19:39:55
2011-12-05T19:39:55
2,674,324
0
0
null
null
null
null
UTF-8
C++
false
false
1,864
h
// This file is an example for CGLib. // // CGLib is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // CGLib is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with CGLib; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // Copyright 2007 Carlos Martinho #ifndef MY_FPS_CAMERA_H #define MY_FPS_CAMERA_H #include <string> #include "cg/cg.h" #include "MyPhysics.h" #include "Munition.h" namespace example { class MyFPSCamera : public cg::Entity, public cg::IDrawListener, public cg::IReshapeEventListener, public cg::IMouseEventListener, public cg::IUpdateListener { private: cg::Vector2d _winSize; cg::Vector3d _position; cg::Vector3d _up,_front,_right; cg::Quaterniond _orientation, _q; bool _isRoll, _isFPSMode, _isFirst; GLdouble unchangedModelViewMatrix[ 16 ]; MyPhysics fpsCameraPhysics; public: MyFPSCamera( std::string id ); virtual ~MyFPSCamera(); void init(); void draw(); void onReshape(int width, int height); void toggleFPSMode(); cg::Vector3d getPosition(); bool isActive(); void setPosition(cg::Vector3d position); void onMousePassiveMotion( int x, int y ); void onMouseMotion( int x, int y ); void update( unsigned long ellapsedMilis ); GLdouble* getUnchangedMVMatrix(); GLdouble getRotationX(); bool isFPSMode(); }; } #endif
[ "ivandro_cm@hotmail.com" ]
ivandro_cm@hotmail.com
9b96cba045f64b83d333de70b8f1357d248d7396
5e840fac5f2af50f5a5f2df558385ee54fbed3f3
/src/DebugOut.h
d55f976d5c0c9da9e6106e58d2e6f23a4e4f4792
[]
no_license
nschorer/FruitNinja-minigame
13353bee897f5ee0abe5b75e6d478b0e0932b205
d3f1920c7c9815d006751ad13423f89d644bec50
refs/heads/main
2023-07-02T13:48:01.543605
2021-08-03T21:09:58
2021-08-03T21:09:58
392,453,989
0
0
null
null
null
null
UTF-8
C++
false
false
317
h
#ifndef DEBUG_OUT_H #define DEBUG_OUT_H #include <Windows.h> #include <stdio.h> #include <stdarg.h> class DebugMsg { private: static char DebugBuff[256]; public: static void out(char* A, ...) { va_list args; va_start(args, A); vsprintf_s(DebugBuff, A, args); OutputDebugString(DebugBuff); }; }; #endif
[ "nrschorer@gmail.com" ]
nrschorer@gmail.com
754aed2c340ff9dade1c2e1e78f26d3ce568744d
dee6f6d8ce0dba5c803e042203389d09075a604c
/timus/1036.cpp
718c89ce5415f41c3e72e89fa1b8b28473882ac4
[]
no_license
redcapital/algo
d197a92a43833462034f232f4fd78612c4261422
0cba5a9c3e628755e9a22b3a1b5eb19a0dfe7aad
refs/heads/master
2022-12-25T07:56:19.059333
2022-12-19T15:50:35
2022-12-19T15:50:35
4,259,720
0
0
null
null
null
null
UTF-8
C++
false
false
2,467
cpp
// Uses: dynamic programming, bignum arithmetic // Let d[N][K] be the number of N-digit sequences that sum up to K // The recurrence relation: // d[N + 1][K] = d[N][K] + d[N][K - 1] + d[N][K - 2] ... d[N][K - 9], K - 9 >= 0 // // Obviously d[1][K] = 1 if 0<=K<=9, and 0 otherwise // Answer then would be (d[N][K] ^ 2) since there are two halves of a ticket // and any half can be one of d[N][K] sequences // // K = S / 2, where S is second number in input. If S is odd answer is 0 // // Since d[i][] depends only on d[i-1][], we can use only 2 arrays with K elements // Also, answers can be very big so we must use bignum arithmetic #include <iostream> #include <cstdio> #include <vector> using namespace std; const int BASE = 1000000000; class LongNum : public vector<int> { public: LongNum() {} void operator=(int x) { clear(); do { push_back(x % BASE); x /= BASE; } while (x); } void add(LongNum& a) { int carry = 0, ml = max(size(), a.size()); for (int i = 0; i < ml || carry; i++) { if (i == size()) push_back(0); (*this)[i] = (i < size() ? (*this)[i] : 0) + (i < a.size() ? a[i] : 0) + carry; carry = ((*this)[i] >= BASE) ? 1 : 0; if (carry) (*this)[i] -= BASE; } } LongNum square() { LongNum result; result.resize(size() * 2); for (int i = 0; i < size(); i++) for (int j = 0, carry = 0; j < size() || carry; j++) { long long cur = result[i + j] + (*this)[i] * 1ll * (j < size() ? (*this)[j] : 0) + carry; result[i + j] = int(cur % BASE); carry = int(cur / BASE); } while (result.size() > 1 && result.back() == 0) result.pop_back(); return result; } void print() { if (empty()) cout << 0; else { printf("%d", back()); for (int i = (int)size() - 2; i >= 0; i--) { printf("%09d", (*this)[i]); } } } }; int main(int argc, char const *argv[]) { int n, k; cin >> n >> k; if (k % 2 == 0) { int i, j, r; LongNum d[2][501]; k /= 2; for (i = 0; i <= k; i++) d[0][i] = (i < 10); int cur = 1; for (i = 1; i < n; i++, cur = !cur) { d[cur][0] = 1; for (j = 1; j <= k; j++) { d[cur][j] = 0; for (r = 0; r <= min(9, j); r++) d[cur][j].add(d[1 - cur][j - r]); } } d[1 - cur][k].square().print(); } else cout << 0; cout << endl; return 0; }
[ "kozhayev@gmail.com" ]
kozhayev@gmail.com
27225de1b4aaf3f953504d396a6528d3d802939a
2a8826a62b0a19a8929aaea2059537af9958f699
/fonction/src/test_fonction.cpp
c714a7125694fcae366c7e88f5aa394ea61cb3db
[]
no_license
ArnaudParan/TP-MOPSI
1f51bc7a7faa3b0287b4a9319690898068b033e6
c59ecc33b514eb6c2867012e73679ea39cab127a
refs/heads/master
2021-01-13T00:55:25.244734
2015-11-16T09:08:19
2015-11-16T09:08:19
43,055,061
0
0
null
null
null
null
UTF-8
C++
false
false
1,018
cpp
#include "test_fonction.hpp" #define ABS(val) ((val >= 0) ? val : -val) void Test_Fonction::setUp() { this->foncTest = NULL; this->foncTest = new FonctionCarre; } void Test_Fonction::tearDown() { delete this->foncTest; this->foncTest = NULL; } void Test_Fonction::test_inverse() { double image = 2.; double antecedant = (this->foncTest)->inverse(image); double image_calculee = (*(this->foncTest))(antecedant); double erreur = ABS(image_calculee - image); double erreur_max = 1e-5; CPPUNIT_ASSERT(erreur <= erreur_max); } void Test_Fonction::test_derivee() { Fonction* derivee = this->foncTest->derivee(); double antecedant = 1.; double image_attendue = 2.; double image = (*derivee)(antecedant); double erreur = ABS(image - image_attendue); double erreur_max = 1e-5; CPPUNIT_ASSERT(erreur <= erreur_max); delete derivee; } FonctionCarre::FonctionCarre() { } FonctionCarre::~FonctionCarre() { } double FonctionCarre::operator()(double antecedant) const { return antecedant * antecedant; }
[ "paran.arnaud@gmail.com" ]
paran.arnaud@gmail.com
c7ddaceb3ade4abc70f9f0e8eaf2072322279c1d
1af49694004c6fbc31deada5618dae37255ce978
/third_party/blink/renderer/modules/content_index/content_index.h
f159dd7c586429e346c315c87e1bd8ff9e33257a
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
sadrulhc/chromium
59682b173a00269ed036eee5ebfa317ba3a770cc
a4b950c23db47a0fdd63549cccf9ac8acd8e2c41
refs/heads/master
2023-02-02T07:59:20.295144
2020-12-01T21:32:32
2020-12-01T21:32:32
317,678,056
3
0
BSD-3-Clause
2020-12-01T21:56:26
2020-12-01T21:56:25
null
UTF-8
C++
false
false
3,203
h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CONTENT_INDEX_CONTENT_INDEX_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_CONTENT_INDEX_CONTENT_INDEX_H_ #include "base/memory/scoped_refptr.h" #include "base/sequenced_task_runner.h" #include "third_party/blink/public/mojom/content_index/content_index.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink { class ContentDescription; class ExceptionState; class ScriptPromiseResolver; class ScriptState; class ServiceWorkerRegistration; class ContentIndex final : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: ContentIndex(ServiceWorkerRegistration* registration, scoped_refptr<base::SequencedTaskRunner> task_runner); ~ContentIndex() override; // Web-exposed function defined in the IDL file. ScriptPromise add(ScriptState* script_state, const ContentDescription* description, ExceptionState& exception_state); ScriptPromise deleteDescription(ScriptState* script_state, const String& id, ExceptionState& exception_state); ScriptPromise getDescriptions(ScriptState* script_state, ExceptionState& exception_state); void Trace(Visitor* visitor) const override; private: mojom::blink::ContentIndexService* GetService(); // Callbacks. void DidGetIconSizes(ScriptPromiseResolver* resolver, mojom::blink::ContentDescriptionPtr description, const Vector<gfx::Size>& icon_sizes); void DidGetIcons(ScriptPromiseResolver* resolver, mojom::blink::ContentDescriptionPtr description, Vector<SkBitmap> icons); void DidCheckOfflineCapability( ScriptPromiseResolver* resolver, KURL launch_url, mojom::blink::ContentDescriptionPtr description, Vector<SkBitmap> icons, bool is_offline_capable); void DidAdd(ScriptPromiseResolver* resolver, mojom::blink::ContentIndexError error); void DidDeleteDescription(ScriptPromiseResolver* resolver, mojom::blink::ContentIndexError error); void DidGetDescriptions( ScriptPromiseResolver* resolver, mojom::blink::ContentIndexError error, Vector<mojom::blink::ContentDescriptionPtr> descriptions); Member<ServiceWorkerRegistration> registration_; scoped_refptr<base::SequencedTaskRunner> task_runner_; HeapMojoRemote<mojom::blink::ContentIndexService, HeapMojoWrapperMode::kWithoutContextObserver> content_index_service_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CONTENT_INDEX_CONTENT_INDEX_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
76e3b3d03ff71a0a2cebd2d53cb2151a225b52a2
3e002355d10972485fb1979aa6e98aaa29f1dacb
/Camerun(NewVersion)/FontSprite3D.cpp
d1ca3fe6e7e9ed6e46025e497727509317c5217f
[]
no_license
Taka03/Camerun2
9f6289d0230d193d146d1209c7f1056819caa9f7
c4dfde2b86c60503284a59f3716913f991ee6e56
refs/heads/master
2020-06-04T21:17:50.490601
2013-05-07T12:26:22
2013-05-07T12:26:22
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,827
cpp
//*============================================================================ //FontSprite3D.cpp //*============================================================================ //============================================================================= //include //============================================================================= #include "FontSprite3D.h" #include "SceneManager.h" //============================================================================ //コンストラクタ //============================================================================ //[input] // pName:データ名 //=========================================================================== CFontSprite3D::CFontSprite3D( const char *pName, Math::Vector3D vPos ) :m_pFontSpr3D(NULL), CDraw3DObject( pName, vPos ) { m_Str = "あああああ"; for( int i = 0;i < SCREEN_MAX;++i ) { m_pActorFont[i] = NULL; } m_fSize.x = 1.0f; m_fSize.y = -11.0f; } //============================================================================ //デストラクタ //============================================================================ CFontSprite3D::~CFontSprite3D(void) { for( int i = 0;i < SCREEN_MAX;++i ) { SAFE_RELEASE( m_pActorFont[i] ); } SAFE_RELEASE( m_pFontSpr3D ); SAFE_RELEASE( m_pRender ); } //============================================================================ //ファイル読み込み //============================================================================ //[input] // pRender:レンダラー用デバイス // pFileMgr:ファイル管理用デバイス //=========================================================================== void CFontSprite3D::Load( Renderer::IRender *pRender, File::IFileManager *pFileMgr ) { pFileMgr->SetCurrentPath("Font"); m_pFontSpr3D = pRender->CreateFontSprite3DFromFile( m_strFileName.c_str(), "tga", 1024 ); m_pRender = pRender; m_pRender->AddRef(); //アクターの生成 for( int i = 0;i < SCREEN_MAX;++i ) { CreateActor( i, CCommonObject::GetSceneMgr( i )->GetSceneMgr() ); } } //============================================================================ //ファイル読み込み //============================================================================ //[input] // pRender:レンダラー用デバイス //=========================================================================== void CFontSprite3D::CreateActor( int index, Scene::ISceneManager *pSceneMgr ) { m_pActorFont[index] = pSceneMgr->CreateActor( m_pFontSpr3D ); } //============================================================================ //処理 //============================================================================ void CFontSprite3D::Exec() { if( m_pFontSpr3D != NULL ) { // 文字列描画用のステート m_pRender->SetDrawType( DRAW_TYPE_BLEND ); m_pRender->SetAlphaTestEnable( true ); m_pRender->SetDepthTestEnable( true ); m_pRender->SetDepthWriteEnable( true ); m_pRender->SetCullType( CULL_FRONT ); /*描画開始*/ m_pFontSpr3D->Begin(); /*描画キューに追加*/ m_pFontSpr3D->DrawString( m_Str.c_str(), m_vPos, m_fSize, CColor(255, 255, 255) ); /*描画終了*/ m_pFontSpr3D->End(); } } //============================================================================ //レンダリング //============================================================================ void CFontSprite3D::Rendering() { if( GetVisibleFlag() ) { m_pActorFont[m_ActorIndex]->RenderingRequest(); } } //============================================================================ //アクターインデックスのセット //============================================================================ void CFontSprite3D::SetActorIndex( int index ) { m_ActorIndex = index; }
[ "luigemansion@yahoo.co.jp" ]
luigemansion@yahoo.co.jp
daf322f38b32747e57c6b81fb88ad4da9c249faf
ea00e619d7504f2346b2fd437b3d1d77b918ff7c
/lib/gram.cpp
e4352abb6793da5d0498d78f0e39d9f6ea91fb0d
[]
no_license
nishiokozo/hv
1e93aa25138b22eb09ffa76a9ddb68ad92d74ae5
1b30678f82adb926dd6eb23119a12bd074ae16c3
refs/heads/master
2020-03-28T16:12:31.798659
2019-04-15T16:39:56
2019-04-15T16:39:56
148,669,988
0
0
null
null
null
null
UTF-8
C++
false
false
3,963
cpp
#include <iostream> using namespace std; #include <string> #include <stdio.h> #include <math.h> #include <ctype.h> #include <windows.h> #undef APIENTRY #include <GL/glew.h> #undef GLEWAPI #include <GL/wglew.h> //#include "vec.h" //#include "gl.h" #include "bmp.h" //-- //#include "texture.h" #include "gram.h" //------------------------------------------------------------------------------ Gram::~Gram() //------------------------------------------------------------------------------ { free( m_pBuf ); m_pBuf = 0; } //------------------------------------------------------------------------------ Gram::Gram( int width, int height ) // , int type, bool nearest_linear ) //------------------------------------------------------------------------------ { memset( this, 0, sizeof(*this) ); // m_type = type; { m_width = width; m_height = height; m_pBuf = (float*)malloc( m_width*m_height*sizeof(float[4]) ); // int min = nearest_linear ? GL_LINEAR : GL_NEAREST; // int mag = nearest_linear ? GL_LINEAR : GL_NEAREST; // m_pTexture = new Texture( GL_TEXTURE_2D, GL_RGBA32F, m_width, m_height, min, mag, GL_REPEAT, GL_REPEAT ); } for( int py = 0 ; py < m_height ; py++ ) { for( int px = 0 ; px < m_width ; px++ ) { PutColor( px, py, 0,0,0); } } } //------------------------------------------------------------------------------ void Gram::Clear() //------------------------------------------------------------------------------ { for ( int y = 0 ; y < m_height ; y++ ) for ( int x = 0 ; x < m_width ;x++ ) { // int h = m_height - y-1; float* ptr = &m_pBuf[ ( m_width*y + x ) * 4 ]; ptr[0] = 0; ptr[1] = 0; ptr[2] = 0; ptr[3] = 0; } } //------------------------------------------------------------------------------ void Gram::GetColor( int x, int y, float& r, float& g, float& b ) //------------------------------------------------------------------------------ { if ( x >= 0 && x < m_width && y >= 0 && y < m_height ) { y = m_height - y-1; float* ptr = &m_pBuf[ ( m_width*y + x ) * 4 ]; r = ptr[0]; g = ptr[1]; b = ptr[2]; } } //------------------------------------------------------------------------------ void Gram::FillColor( int x, int y, float* fm, int w, int h ) //------------------------------------------------------------------------------ { for ( int i = 0 ; i < h ; i++ ) { int yy = y+i; if ( yy >= 0 && yy < m_height ) { for ( int j = 0 ; j < w ; j++ ) { int xx = x+j; if ( xx >=0 && xx < m_width ) { float* to = &m_pBuf[ ( m_width*yy + xx ) * 4 ]; to[0] = *fm++; to[1] = *fm++; to[2] = *fm++; to[3] = *fm++; } else { fm+=4; } } } else { fm+=4*w; } } } //------------------------------------------------------------------------------ void Gram::PutColor( int x, int y, float r, float g, float b ) //------------------------------------------------------------------------------ { if ( x >= 0 && x < m_width && y >= 0 && y < m_height ) { // y = m_height - y-1; float* ptr = &m_pBuf[ ( m_width*y + x ) * 4 ]; ptr[0] = r; ptr[1] = g; ptr[2] = b; ptr[3] = 1.0; } } //------------------------------------------------------------------------------ void Gram::Load( float* fm, int w, int h ) //------------------------------------------------------------------------------ { float* to = m_pBuf; for ( int y = 0 ; y < m_height ; y++ ) for ( int x = 0 ; x < m_width ; x++ ) { if ( x < w && y < h ) { to[0] = *fm++; to[1] = *fm++; to[2] = *fm++; to[3] = *fm++; } to += 4; } } /* //------------------------------------------------------------------------------ void Gram::UpdateTexture() //------------------------------------------------------------------------------ { m_pTexture->LoadTexture( m_width, m_height, GL_RGBA, GL_FLOAT, m_pBuf ); } */
[ "nishiokozo@gmail.com" ]
nishiokozo@gmail.com
3192117a057760c50418cec23374c3a75dd07cb5
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE191_Integer_Underflow/s02/CWE191_Integer_Underflow__int_fgets_sub_43.cpp
1ffff0bf26ce7d2f6a2ab371d3552a8c103999ec
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,803
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__int_fgets_sub_43.cpp Label Definition File: CWE191_Integer_Underflow__int.label.xml Template File: sources-sinks-43.tmpl.cpp */ /* * @description * CWE: 191 Integer Underflow * BadSource: fgets Read data from the console using fgets() * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: sub * GoodSink: Ensure there will not be an underflow before subtracting 1 from data * BadSink : Subtract 1 from data, which can cause an Underflow * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file * * */ #include "std_testcase.h" #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) namespace CWE191_Integer_Underflow__int_fgets_sub_43 { #ifndef OMITBAD static void badSource(int &data) { { char inputBuffer[CHAR_ARRAY_SIZE] = ""; /* POTENTIAL FLAW: Read data from the console using fgets() */ if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) { /* Convert to int */ data = atoi(inputBuffer); } else { printLine("fgets() failed."); } } } void bad() { int data; /* Initialize data */ data = 0; badSource(data); { /* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow */ int result = data - 1; printIntLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSource(int &data) { /* FIX: Use a small, non-zero value that will not cause an integer underflow in the sinks */ data = -2; } static void goodG2B() { int data; /* Initialize data */ data = 0; goodG2BSource(data); { /* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow */ int result = data - 1; printIntLine(result); } } /* goodB2G() uses the BadSource with the GoodSink */ static void goodB2GSource(int &data) { { char inputBuffer[CHAR_ARRAY_SIZE] = ""; /* POTENTIAL FLAW: Read data from the console using fgets() */ if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) { /* Convert to int */ data = atoi(inputBuffer); } else { printLine("fgets() failed."); } } } static void goodB2G() { int data; /* Initialize data */ data = 0; goodB2GSource(data); /* FIX: Add a check to prevent an underflow from occurring */ if (data > INT_MIN) { int result = data - 1; printIntLine(result); } else { printLine("data value is too large to perform subtraction."); } } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE191_Integer_Underflow__int_fgets_sub_43; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
c58f72157388edda401e1d84b6637985dc49e4f0
e8b97d2503ab3c8939cd6cad946355dcbc0c67b9
/sensors/cameras/flycapture/flycapture.cpp
2f28640adc00bad17967e283fd9225a3e86ef02d
[ "BSD-2-Clause" ]
permissive
wangfei-824/snark
a5c600c70f3fedb87fe9ba4b1a01b1b999862ee6
f4f50a95a2a7dbccc82ee6f2e5026e9ab7c7f8b4
refs/heads/master
2021-06-08T03:06:14.910744
2016-06-10T07:41:28
2016-06-10T07:41:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,138
cpp
// This file is part of snark, a generic and flexible library for robotics research // Copyright (c) 2011 The University of Sydney // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the University of Sydney nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT // HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <boost/thread.hpp> #include <boost/assign.hpp> #include <boost/bimap.hpp> #include <comma/base/exception.h> #include <comma/application/signal_flag.h> #include <comma/csv/stream.h> #include "flycapture.h" //using namespace FlyCapture2; // static void PVDECL pv_callback_( tPvFrame *frame ); /*TODO: * Discard argument is ignored. * implement a callback solution */ namespace snark{ namespace camera{ static const unsigned int max_retries = 15; typedef boost::bimap<FlyCapture2::PixelFormat , std::string> pixel_format_map_t; static const pixel_format_map_t pixel_format_map = boost::assign::list_of< pixel_format_map_t::relation > (FlyCapture2::PIXEL_FORMAT_MONO8, "PIXEL_FORMAT_MONO8") (FlyCapture2::PIXEL_FORMAT_411YUV8, "PIXEL_FORMAT_411YUV8") /**< YUV 4:1:1. */ (FlyCapture2::PIXEL_FORMAT_422YUV8, "PIXEL_FORMAT_422YUV8") /**< YUV 4:2:2. */ (FlyCapture2::PIXEL_FORMAT_444YUV8, "PIXEL_FORMAT_444YUV8") /**< YUV 4:4:4. */ (FlyCapture2::PIXEL_FORMAT_RGB8 , "PIXEL_FORMAT_RGB8") /**< R = G = B = 8 bits. */ (FlyCapture2::PIXEL_FORMAT_MONO16 , "PIXEL_FORMAT_MONO16") /**< 16 bits of mono information. */ (FlyCapture2::PIXEL_FORMAT_RGB16 , "PIXEL_FORMAT_RGB16") /**< R = G = B = 16 bits. */ (FlyCapture2::PIXEL_FORMAT_S_MONO16, "PIXEL_FORMAT_S_MONO16") /**< 16 bits of signed mono information. */ (FlyCapture2::PIXEL_FORMAT_S_RGB16 , "PIXEL_FORMAT_S_RGB16") /**< R = G = B = 16 bits signed. */ (FlyCapture2::PIXEL_FORMAT_RAW8 , "PIXEL_FORMAT_RAW8") /**< 8 bit raw data output of sensor. */ (FlyCapture2::PIXEL_FORMAT_RAW16 , "PIXEL_FORMAT_RAW16") /**< 16 bit raw data output of sensor. */ (FlyCapture2::PIXEL_FORMAT_MONO12 , "PIXEL_FORMAT_MONO12") /**< 12 bits of mono information. */ (FlyCapture2::PIXEL_FORMAT_RAW12 , "PIXEL_FORMAT_RAW12") /**< 12 bit raw data output of sensor. */ (FlyCapture2::PIXEL_FORMAT_BGR , "PIXEL_FORMAT_BGR") /**< 24 bit BGR. */ (FlyCapture2::PIXEL_FORMAT_BGRU , "PIXEL_FORMAT_BGRU") /**< 32 bit BGRU. */ // (FlyCapture2::PIXEL_FORMAT_RGB ,"PIXEL_FORMAT_RGB") /**< 24 bit RGB. same as RGB8*/ (FlyCapture2::PIXEL_FORMAT_RGBU , "PIXEL_FORMAT_RGBU") /**< 32 bit RGBU. */ (FlyCapture2::PIXEL_FORMAT_BGR16 , "PIXEL_FORMAT_BGR16") /**< R = G = B = 16 bits. */ (FlyCapture2::PIXEL_FORMAT_BGRU16 , "PIXEL_FORMAT_BGRU16") /**< 64 bit BGRU. */ (FlyCapture2::PIXEL_FORMAT_422YUV8_JPEG, "PIXEL_FORMAT_422YUV8_JPEG")/**< JPEG compressed stream. */ (FlyCapture2::NUM_PIXEL_FORMATS , "NUM_PIXEL_FORMATS") /**< Number of pixel formats. */ (FlyCapture2::UNSPECIFIED_PIXEL_FORMAT, "UNSPECIFIED_PIXEL_FORMAT"); typedef boost::bimap<FlyCapture2::PropertyType ,std::string > property_map_t; property_map_t property_map = boost::assign::list_of<property_map_t::relation> (FlyCapture2::BRIGHTNESS, "brightness") (FlyCapture2::AUTO_EXPOSURE, "auto_exposure") (FlyCapture2::SHARPNESS, "sharpness") (FlyCapture2::WHITE_BALANCE, "white_balance") (FlyCapture2::HUE, "hue") (FlyCapture2::SATURATION, "saturation") (FlyCapture2::GAMMA, "gamma") (FlyCapture2::IRIS, "iris") (FlyCapture2::FOCUS, "focus") (FlyCapture2::ZOOM, "zoom") (FlyCapture2::PAN, "pan") (FlyCapture2::TILT, "tilt") (FlyCapture2::SHUTTER, "shutter") (FlyCapture2::GAIN, "gain") //(FlyCapture2::TRIGGER_MODE, "trigger_mode") //Not supported properly through PropertyType //(FlyCapture2::TRIGGER_DELAY, "trigger_delay") //There is a separate function set for trigger modes (FlyCapture2::FRAME_RATE, "frame_rate") (FlyCapture2::TEMPERATURE, "temperature"); //List for attributes that exist inside structs in the API, so they have to be listed directly static const std::vector< std::string > explicit_attributes = boost::assign::list_of ( "maxWidth" ) ( "maxHeight" ) ( "offsetHStepSize" ) ( "offsetVStepSize" ) ( "offsetX" ) ( "offsetY" ) ( "width" ) ( "height" ) ( "PixelFormat" ) ( "trigger_on" ) ( "trigger_mode" ) ( "trigger_parameter" ) ( "trigger_polarity" ) ( "trigger_source" ); static std::string flycapture_get_attribute_( FlyCapture2::GigECamera& handle, const std::string& key ) { FlyCapture2::Error error; FlyCapture2::GigEImageSettings image_settings; FlyCapture2::GigEImageSettingsInfo image_settings_info; FlyCapture2::TriggerMode trigger_mode; error = handle.GetGigEImageSettings(&image_settings); error = handle.GetGigEImageSettingsInfo(&image_settings_info); error = handle.GetTriggerMode(&trigger_mode); /***/if ( key == "maxWidth" ) return boost::to_string( image_settings_info.maxWidth ); else if ( key == "maxHeight" ) return boost::to_string( image_settings_info.maxHeight ); else if ( key == "offsetHStepSize" ) return boost::to_string( image_settings_info.offsetHStepSize ); else if ( key == "offsetVStepSize" ) return boost::to_string( image_settings_info.offsetVStepSize ); else if ( key == "offsetX" ) return boost::to_string( image_settings.offsetX ); else if ( key == "offsetY" ) return boost::to_string( image_settings.offsetY ); else if ( key == "width" ) return boost::to_string( image_settings.width ); else if ( key == "height" ) return boost::to_string( image_settings.height ); else if ( key == "PixelFormat" ) return pixel_format_map.left.at( image_settings.pixelFormat ); else if ( key == "trigger_on" ) return boost::to_string( trigger_mode.onOff ); else if ( key == "trigger_polarity" ) return boost::to_string( trigger_mode.polarity ); else if ( key == "trigger_source" ) return boost::to_string( trigger_mode.source ); else if ( key == "trigger_mode" ) return boost::to_string( trigger_mode.mode ); else if ( key == "trigger_parameter" ) return boost::to_string( trigger_mode.parameter ); //Check the property list else{ if( property_map.right.find(key) != property_map.right.end() ) { FlyCapture2::Property cam_prop; FlyCapture2::PropertyInfo cam_prop_info; cam_prop.type = property_map.right.at( key ); cam_prop_info.type = property_map.right.at( key ); handle.GetProperty( &cam_prop ); handle.GetPropertyInfo( &cam_prop_info ); if( !cam_prop.present ) return "N/A"; //If property is not present, it is unsupported for this camera if( cam_prop.autoManualMode ) return "auto"; if( cam_prop.type == FlyCapture2::WHITE_BALANCE ) //White balance has two values, so it is a special case return boost::to_string( cam_prop.valueA ) + "," + boost::to_string( cam_prop.valueB ); return boost::to_string( cam_prop.absControl ? cam_prop.absValue : cam_prop.valueA ); } else { std::cerr << "flycapture-cat error: property '" << key << "' not found!" << std::endl; } } return "Not Found"; } static void flycapture_set_attribute_( FlyCapture2::GigECamera& handle, const std::string& key, const std::string& value ) { FlyCapture2::Error error; FlyCapture2::GigEConfig cam_config; FlyCapture2::GigEImageSettings image_settings; FlyCapture2::GigEImageSettingsInfo image_settings_info; FlyCapture2::TriggerMode trigger_mode; error = handle.GetGigEImageSettings(&image_settings); if(error != FlyCapture2::PGRERROR_OK) {COMMA_THROW( comma::exception, "Error getting attributes from camera." );} error = handle.GetGigEImageSettingsInfo(&image_settings_info); if(error != FlyCapture2::PGRERROR_OK) {COMMA_THROW( comma::exception, "Error getting attributes from camera." );} error = handle.GetTriggerMode(&trigger_mode); if(error != FlyCapture2::PGRERROR_OK) {COMMA_THROW( comma::exception, "Error getting attributes from camera.");} /**/ if ( key == "offsetHStepSize" ) image_settings_info.offsetHStepSize = boost::lexical_cast<int>(value); else if ( key == "offsetVStepSize" ) image_settings_info.offsetVStepSize = boost::lexical_cast<int>(value); else if ( key == "offsetX" ) image_settings.offsetX = boost::lexical_cast<int>(value); else if ( key == "offsetY" ) image_settings.offsetY = boost::lexical_cast<int>(value); else if ( key == "width" ) { if(( boost::lexical_cast<uint>( value ) > image_settings_info.maxWidth ) | ( boost::lexical_cast<uint>( value ) < 0 )) { COMMA_THROW( comma::exception, "Error: width out of bounds" ); } else { image_settings.width = boost::lexical_cast<int>( value ); } } else if ( key == "height" ) { if(( boost::lexical_cast<uint>( value ) > image_settings_info.maxHeight ) | ( boost::lexical_cast<uint>( value ) < 0 )) { COMMA_THROW( comma::exception, "Error: height out of bounds" ); } else { image_settings.height = boost::lexical_cast<int>( value ); } } else if ( key == "PixelFormat" ) { if( pixel_format_map.right.find(value) != pixel_format_map.right.end() ) { image_settings.pixelFormat = pixel_format_map.right.at( value ); } else { COMMA_THROW( comma::exception, "Error: invalid pixel format."); } } else if ( key == "trigger_on" ) { if ( value == "true" ) {trigger_mode.onOff = true;} else if ( value == "false" ) {trigger_mode.onOff = false;} else {COMMA_THROW( comma::exception, "Error: invalid trigger_on setting. Please use true/false" );} } else if ( key == "trigger_polarity" ) { if ( value == "high" ) {trigger_mode.polarity = 1;} else if ( value == "low" ) {trigger_mode.polarity = 0;} else {COMMA_THROW( comma::exception, "Error: invalid trigger_polarity setting. Please use high/low");} } else if ( key == "trigger_source" ) // 0-3 are GPIO, 4 = none { /**/ if( value == "GPIO0" ) {trigger_mode.source = 0;} else if( value == "GPIO1" ) {trigger_mode.source = 1;} else if( value == "GPIO2" ) {trigger_mode.source = 2;} else if( value == "GPIO3" ) {trigger_mode.source = 3;} else if( value == "none" ) {trigger_mode.source = 4;} else if( value == "software" ) {trigger_mode.source = 7;} else {COMMA_THROW( comma::exception, "Error: unknown trigger source. please use 'GPIO[0-3]', 'software' or 'none'");} } else if ( key == "trigger_mode" ) {trigger_mode.mode = boost::lexical_cast<int>(value);} else if ( key == "trigger_parameter" ) {trigger_mode.parameter = boost::lexical_cast<int>(value);} //Check the property list else{ if( property_map.right.find( key ) != property_map.right.end() ) { FlyCapture2::Property cam_prop; FlyCapture2::PropertyInfo cam_prop_info; cam_prop.type = property_map.right.at( key ); cam_prop_info.type = property_map.right.at( key ); handle.GetProperty( &cam_prop ); handle.GetPropertyInfo( &cam_prop_info ); if( !cam_prop.present ) return; //If property is not present, it is unsupported for this camera if( value == "auto" ) cam_prop.autoManualMode = true; else { cam_prop.autoManualMode = false; if( cam_prop.type == FlyCapture2::WHITE_BALANCE ) //White balance has two values, so it is a special case { std::vector< std::string > v = comma::split( value, "," ); if(v.size() != 2) { COMMA_THROW( comma::exception, "Error: White Balance must be in the format of 'red,blue' or 'auto' where red and blue are integers [0,1023]" ); } else { cam_prop.valueA = boost::lexical_cast<uint>( v[0] ); cam_prop.valueB = boost::lexical_cast<uint>( v[1] ); } } else { if( value.find( "." ) != value.npos ) { cam_prop.absControl = true; cam_prop.absValue = boost::lexical_cast<float>( value ); } else { cam_prop.absControl = false; cam_prop.valueA = boost::lexical_cast<uint>( value ); } } } error = handle.SetProperty( &cam_prop ); if(error != FlyCapture2::PGRERROR_OK) COMMA_THROW( comma::exception, "Error setting attributes: " << error.GetDescription() ); } else { COMMA_THROW( comma::exception, "Error: property '" << key << "' not found!" ); } } //Handle errors here, the SDK should do out of bounds checking error = handle.SetGigEImageSettings( &image_settings ); if( error != FlyCapture2::PGRERROR_OK ) { COMMA_THROW( comma::exception, "Error setting attributes." );} error = handle.SetTriggerMode( &trigger_mode ); if( error != FlyCapture2::PGRERROR_OK ) { COMMA_THROW( comma::exception, "Error setting attributes." );} return; } flycapture::attributes_type flycapture_attributes_( FlyCapture2::GigECamera& handle ) { flycapture::attributes_type attributes; for( std::vector< std::string >::const_iterator i = explicit_attributes.begin(); i != explicit_attributes.end(); i++ ) { attributes.insert( std::make_pair( *i, flycapture_get_attribute_( handle, *i ) ) ); } //There is an iterable list for the remaining attributes for( property_map_t::const_iterator i = property_map.begin(); i != property_map.end(); ++i ) { attributes.insert( std::make_pair( i->right , flycapture_get_attribute_( handle,i->right ) ) ); } return attributes; } unsigned int flycapture_bits_per_pixel_( const FlyCapture2::PixelFormat pixel_format_ ) { switch( pixel_format_ ) { case FlyCapture2::PIXEL_FORMAT_MONO8: case FlyCapture2::PIXEL_FORMAT_RAW8: return 8; break; case FlyCapture2::PIXEL_FORMAT_RAW16: case FlyCapture2::PIXEL_FORMAT_MONO16: return 16; case FlyCapture2::PIXEL_FORMAT_RGB: case FlyCapture2::PIXEL_FORMAT_BGR: return 24; case FlyCapture2::PIXEL_FORMAT_RGBU: case FlyCapture2::PIXEL_FORMAT_BGRU: return 32; case FlyCapture2::PIXEL_FORMAT_RGB16: return 48; case FlyCapture2::PIXEL_FORMAT_411YUV8: case FlyCapture2::PIXEL_FORMAT_422YUV8: case FlyCapture2::PIXEL_FORMAT_444YUV8: COMMA_THROW( comma::exception, "unsupported format " << pixel_format_ ); default: COMMA_THROW( comma::exception, "unknown format " << pixel_format_ ); return 0; } } cv::Mat flycapture_image_as_cvmat_( const FlyCapture2::Image& frame ) { int type; switch( flycapture_bits_per_pixel_(frame.GetPixelFormat() ) ) { case 8: type = CV_8UC1; break; case 16: type = CV_16UC1; break; case 24: type = CV_8UC3; break; case 32: type = CV_8UC4; break; case 48: type = CV_16UC3; break; default: COMMA_THROW( comma::exception, "unknown format " << frame.GetPixelFormat() ); }; return cv::Mat( frame.GetRows(), frame.GetCols(), type, frame.GetData() ); } int flycapture_get_cv_type_( const FlyCapture2::Image& frame ) { switch( flycapture_bits_per_pixel_(frame.GetPixelFormat() ) ) { case 8: return CV_8UC1; case 16: return CV_16UC1; case 24: return CV_8UC3; case 32:return CV_8UC4; case 48: return CV_16UC3; default: COMMA_THROW( comma::exception, "unknown format " << frame.GetPixelFormat() ); }; } bool flycapture_collect_frame_(cv::Mat & image, FlyCapture2::GigECamera& handle, bool & started) { FlyCapture2::Error result; FlyCapture2::Image frame_; FlyCapture2::Image raw_image; result = handle.RetrieveBuffer(&raw_image); frame_.DeepCopy(&raw_image); raw_image.ReleaseBuffer(); if( result == FlyCapture2::PGRERROR_OK ) { cv::Mat cv_image( frame_.GetRows(), frame_.GetCols(), flycapture_get_cv_type_( frame_ ), frame_.GetData() ); cv_image.copyTo(image); return true; } else if( result == FlyCapture2::PGRERROR_IMAGE_CONSISTENCY_ERROR ) { //report damaged frame and try again FlyCapture2::CameraInfo camera_info; handle.GetCameraInfo(&camera_info); std::cerr << "flycapture-cat error: " << result.GetDescription() << "from camera: " << camera_info.serialNumber << " Retrying..." << std::endl; return false; } else if ( ( result == FlyCapture2::PGRERROR_ISOCH_START_FAILED ) //These are errors that result in a retry | ( result == FlyCapture2::PGRERROR_ISOCH_ALREADY_STARTED ) | ( result == FlyCapture2::PGRERROR_ISOCH_NOT_STARTED ) ) { std::cerr << "flycapture-cat error: " << result.GetDescription() << " Restarting camera." << std::endl; handle.StopCapture(); started = false; return false; } else { //Fatal FlyCapture2::CameraInfo camera_info; handle.GetCameraInfo(&camera_info); COMMA_THROW( comma::exception, "got frame with invalid status on camera " << camera_info.serialNumber << ": " << result.GetType() << ": " << result.GetDescription() ); } } class flycapture::impl { //Note, for Point Grey, the serial number is used as ID public: impl( unsigned int id, const attributes_type& attributes, unsigned int id_stereo_camera ) : started_( false ), timeOut_( 1000 ) { initialize_(); stereo = false; if( id_stereo_camera != 0 ) {stereo = true; } static const boost::posix_time::time_duration timeout = boost::posix_time::seconds( 5 ); // quick and dirty; make configurable? boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); boost::posix_time::ptime end = now + timeout; unsigned int size = 0; for( ; now < end; now = boost::posix_time::microsec_clock::universal_time() ) { const std::vector< FlyCapture2::CameraInfo >& list = list_cameras(); size = list.size(); for( unsigned int i = 0; i < list.size(); ++i ) // look for a point grey camera that matches the serial number { if(list[i].interfaceType == FlyCapture2::INTERFACE_GIGE && (id == 0)) { id_ = list[i].serialNumber; } if(list[i].interfaceType == FlyCapture2::INTERFACE_GIGE && ( id == list[i].serialNumber )) { id_ = list[i].serialNumber; } if(list[i].interfaceType == FlyCapture2::INTERFACE_GIGE && ( id_stereo_camera == list[i].serialNumber )) { id_stereo_camera_ = list[i].serialNumber; } } if( id_ && !stereo ) { break; } if(stereo && id_ && id_stereo_camera_ ) { break; } } if( !id_ ) { COMMA_THROW( comma::exception, "timeout; camera not found" ); } if(stereo && !id_stereo_camera_ ) { COMMA_THROW( comma::exception, "timeout; stereo right camera not found" ); } if( id == 0 && size > 1) { const std::vector< FlyCapture2::CameraInfo >& list = list_cameras(); std::stringstream stream; for( std::size_t i = 0; i < list.size(); ++i ) // todo: serialize properly with name-value { stream << "serial=\"" << list[i].serialNumber << "\"," << "model=\"" << list[i].modelName << "\"" << std::endl; } COMMA_THROW( comma::exception, "no id provided and multiple cameras found: would pick up a random one\n\tavailable cameras:\n" << stream.str() ); } now = boost::posix_time::microsec_clock::universal_time(); end = now + timeout; //Get Point grey unique id (guid) from serial number. guid does not exist in CameraInfo, and so it does not appear in the camera list FlyCapture2::BusManager bus_manager; bus_manager.GetCameraFromSerialNumber( *id_ , &guid ); FlyCapture2::Error result = handle_.Connect( &guid ); for( ; ( result != FlyCapture2::PGRERROR_OK ) && ( now < end ); now = boost::posix_time::microsec_clock::universal_time() ) { boost::thread::sleep( now + boost::posix_time::milliseconds( 10 ) ); result = handle_.Connect(&guid); } if (result != FlyCapture2::PGRERROR_OK){close(); COMMA_THROW( comma::exception, "failed to open point grey camera: " << id << ", Reason: " << result.GetDescription() );} for( attributes_type::const_iterator i = attributes.begin(); i != attributes.end(); ++i ) { flycapture_set_attribute_( handle_, i->first, i->second ); } end = now + timeout; if( stereo ) { bus_manager.GetCameraFromSerialNumber(*id_stereo_camera_, &guid_stereo_camera); FlyCapture2::Error result = handle_stereo_camera_.Connect(&guid_stereo_camera); for( ; ( result != FlyCapture2::PGRERROR_OK ) && ( now < end ); now = boost::posix_time::microsec_clock::universal_time() ) { boost::thread::sleep( now + boost::posix_time::milliseconds( 10 ) ); result = handle_stereo_camera_.Connect(&guid_stereo_camera); } if (result != FlyCapture2::PGRERROR_OK){close(); COMMA_THROW( comma::exception, "failed to open point grey camera: " << id_stereo_camera << ", Reason: " << result.GetDescription() );} } FlyCapture2::CameraInfo camera_info; if(stereo) { handle_stereo_camera_.GetCameraInfo( &camera_info ); } handle_.GetCameraInfo( &camera_info ); if(stereo) { // Trigger mode is used to synchronize shutters between the cameras flycapture_set_attribute_( handle_, "trigger_on", "false" ); flycapture_set_attribute_( handle_stereo_camera_, "trigger_mode", "0" ); flycapture_set_attribute_( handle_stereo_camera_, "trigger_on", "true" ); flycapture_set_attribute_( handle_stereo_camera_, "trigger_source", "GPIO0" ); //An extended packet delay is needed to stop packet collision //TODO Maybe add this to set_attr so that it can be user customisable FlyCapture2::GigEProperty packetDelay; packetDelay.propType = FlyCapture2::PACKET_DELAY; handle_.GetGigEProperty(&packetDelay); packetDelay.value = 2000; handle_.SetGigEProperty(&packetDelay); handle_stereo_camera_.GetGigEProperty(&packetDelay); packetDelay.value = 2100; handle_stereo_camera_.SetGigEProperty(&packetDelay); } uint width; uint height; FlyCapture2::PixelFormat pixel_format; width = boost::lexical_cast<uint>( flycapture_get_attribute_( handle_, "width" ) ); height = boost::lexical_cast<uint>( flycapture_get_attribute_( handle_, "height" ) ); pixel_format = pixel_format_map.right.at( flycapture_get_attribute_( handle_,"PixelFormat" ) ); total_bytes_per_frame_ = ( stereo ? 2 : 1 ) * width * height * flycapture_bits_per_pixel_( pixel_format ) / 8; } ~impl() { close(); } void close() { id_.reset(); if( !handle_.IsConnected() ) { return; } handle_.StopCapture(); handle_.Disconnect(); if( stereo ) { id_stereo_camera_.reset(); if( !handle_stereo_camera_.IsConnected() ) { return; } handle_stereo_camera_.StopCapture(); handle_stereo_camera_.Disconnect(); } //std::cerr << "the camera has been closed" << std::endl; } std::pair< boost::posix_time::ptime, cv::Mat > read() { cv::Mat image_; cv::Mat image_stereo_; std::pair< boost::posix_time::ptime, cv::Mat > pair; bool success = false; unsigned int retries = 0; while( !success && retries < max_retries ) { FlyCapture2::Error result; if( !started_ ) {result = handle_.StartCapture();} // error is not checked as sometimes the camera // will start correctly but return an error started_ = true; if( stereo ) { if(!stereo_camera_started_) {result = handle_stereo_camera_.StartCapture();} stereo_camera_started_ = true; } success = flycapture_collect_frame_( image_, handle_ , started_ ); pair.first = boost::posix_time::microsec_clock::universal_time(); if( success ) { if( !stereo ) { pair.second = image_; } else { success = flycapture_collect_frame_( image_stereo_ , handle_stereo_camera_ , stereo_camera_started_ ); if ( success ) { cv::hconcat( image_ , image_stereo_ , pair.second ); } } } retries++; } if( success ) { return pair; } COMMA_THROW( comma::exception, "Got lots of missing frames or timeouts" << std::endl << std::endl << "it is likely that MTU size on your machine is less than packet size" << std::endl << "check PacketSize attribute (flycapture-cat --list-attributes)" << std::endl << "set packet size (e.g. flycapture-cat --set=PacketSize=1500)" << std::endl << "or increase MTU size on your machine" ); } const FlyCapture2::GigECamera& handle() const { return handle_; } FlyCapture2::GigECamera& handle() { return handle_; } const FlyCapture2::GigECamera& handle_stereo_camera() const { return handle_stereo_camera_; } FlyCapture2::GigECamera& handle_stereo_camera() { return handle_stereo_camera_; } unsigned int id() const { return *id_; } unsigned int id_stereo_camera() const { return *id_stereo_camera_; } unsigned long total_bytes_per_frame() const { return total_bytes_per_frame_; } static std::vector< FlyCapture2::CameraInfo > list_cameras() { initialize_(); static const boost::posix_time::time_duration timeout = boost::posix_time::seconds( 5 ); // quick and dirty; make configurable? boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); boost::posix_time::ptime end = now + timeout; std::vector< FlyCapture2::CameraInfo > list; for( ; now < end; now = boost::posix_time::microsec_clock::universal_time() ) { FlyCapture2::BusManager bus_manager; unsigned int num_cameras; FlyCapture2::Error error; error = bus_manager.GetNumOfCameras( &num_cameras ); if ( error != FlyCapture2::PGRERROR_OK ){ COMMA_THROW( comma::exception, "cannot find point grey cameras"); } FlyCapture2::CameraInfo cam_info[num_cameras]; //BUG DiscoverGigECameras will sometimes crash if there are devices on a different subnet error = FlyCapture2::BusManager::DiscoverGigECameras( cam_info, &num_cameras ); if ( error != FlyCapture2::PGRERROR_OK ){ COMMA_THROW( comma::exception, "cannot discover point grey cameras" ); } //If array is not empty, convert to list and exit if( num_cameras > 0 ) { std::copy( &cam_info[0] , &cam_info[num_cameras] , std::back_inserter( list ) ); break; } boost::thread::sleep( now + boost::posix_time::milliseconds( 10 ) ); } return list; } private: friend class flycapture::callback::impl; FlyCapture2::GigECamera handle_; FlyCapture2::GigECamera handle_stereo_camera_; std::vector< char > buffer_; boost::optional< unsigned int > id_; boost::optional< unsigned int > id_stereo_camera_; FlyCapture2::PGRGuid guid; FlyCapture2::PGRGuid guid_stereo_camera; bool stereo; unsigned long total_bytes_per_frame_; bool started_; bool stereo_camera_started_; unsigned int timeOut_; // milliseconds static void initialize_() // quick and dirty { } }; class flycapture::callback::impl { public: typedef boost::function< void ( const std::pair< boost::posix_time::ptime, cv::Mat >& ) > OnFrame; impl( flycapture& flycapture, OnFrame on_frame ) : on_frame( on_frame ) /* , handle( flycapture.pimpl_->handle() ) , frame( flycapture.pimpl_->frame_ ) */ , good( true ) , is_shutdown( false ) { // tPvErr result; // PvCaptureQueueClear( handle ); // frame.Context[0] = this; // result = PvCaptureStart( handle ); // if( result != ePvErrSuccess ) { COMMA_THROW( comma::exception, "failed to start capturing on camera " << flycapture.pimpl_->id() << ": " << pv_error_to_string_( result ) << " (" << result << ")" ); } // result = PvCaptureQueueFrame( handle, &frame, pv_callback_ ); // if( result != ePvErrSuccess ) { COMMA_THROW( comma::exception, "failed to set capture queue frame on camera " << flycapture.pimpl_->id() << ": " << pv_error_to_string_( result ) << " (" << result << ")" ); } // result = PvCommandRun( handle, "AcquisitionStart" ); // if( result != ePvErrSuccess ) { COMMA_THROW( comma::exception, "failed to start acquisition on camera " << flycapture.pimpl_->id() << ": " << pv_error_to_string_( result ) << " (" << result << ")" ); } } ~impl() { is_shutdown = true; // PvCommandRun( handle, "Acquisitionstop" ); // PvCaptureQueueClear( handle ); // PvCaptureEnd( handle ); // handle.StopCapture(); } OnFrame on_frame; // tPvHandle& handle; // tPvFrame& frame; bool good; bool is_shutdown; }; } } // namespace snark{ namespace camera{ // static void PVDECL pv_callback_( tPvFrame *frame ) // { // snark::camera::flycapture::callback::impl* c = reinterpret_cast< snark::camera::flycapture::callback::impl* >( frame->Context[0] ); // if( c->is_shutdown ) { return; } // std::pair< boost::posix_time::ptime, cv::Mat > m( boost::posix_time::microsec_clock::universal_time(), cv::Mat() ); // if( frame ) { m.second = snark::camera::pv_as_cvmat_( *frame ); } // c->on_frame( m ); // tPvErr result = PvCaptureQueueFrame( c->handle, &c->frame, pv_callback_ ); // if( result != ePvErrSuccess ) { c->good = false; } // } namespace snark{ namespace camera{ flycapture::flycapture( unsigned int id, const flycapture::attributes_type& attributes, unsigned int id_stereo_camera ) : pimpl_( new impl( id, attributes, id_stereo_camera ) ) {} flycapture::~flycapture() { delete pimpl_; } std::pair< boost::posix_time::ptime, cv::Mat > flycapture::read() { return pimpl_->read(); } void flycapture::close() { pimpl_->close(); } std::vector< FlyCapture2::CameraInfo > flycapture::list_cameras() { return flycapture::impl::list_cameras(); } unsigned int flycapture::id() const { return pimpl_->id(); } unsigned int flycapture::id_stereo_camera() const { return pimpl_->id_stereo_camera(); } unsigned long flycapture::total_bytes_per_frame() const { return pimpl_->total_bytes_per_frame(); } flycapture::attributes_type flycapture::attributes() const { return flycapture_attributes_( pimpl_->handle() ); } flycapture::callback::callback( flycapture& flycapture, boost::function< void ( std::pair< boost::posix_time::ptime, cv::Mat > ) > on_frame ) : pimpl_( new callback::impl( flycapture, on_frame ) ) { } flycapture::callback::~callback() { delete pimpl_; } bool flycapture::callback::good() const { return pimpl_->good; } } }// namespace snark{ namespace camera{
[ "a.zyner@acfr.usyd.edu.au" ]
a.zyner@acfr.usyd.edu.au
898c303c4f53ae42c16e77d215aea52ed28b644a
4a2a1fc89bc9f812af2188dc7e345de129ea7583
/completesetup.ino
07198f7fed10338afb4da4ae0d42fa3b918851fa
[]
no_license
kkhetarpal/aumoro
8e901b96a95c0d61f8906c5e7358c4bbfcd78e3c
89c86ee5f6d2dbed1068017191a154ef1472778a
refs/heads/master
2021-01-19T08:14:13.131324
2014-12-08T20:02:47
2014-12-08T20:02:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,371
ino
/* Motor Control. */ //User Input char c, l, r; int speed = 0; int max_speed = 250, reduced_speed = 180; //sensor input variables and pins int sensor1 = A0, sensor2 = A1, sensor3 = A2; float sensor1Value = 0, sensor2Value = 0, sensor3Value = 0; float new_sensor1Value = 0, new_sensor2Value = 0, new_sensor3Value = 0; //states int state = 0; int left,right,front; // pins for the Motor 1: const int M1_dir1 = 50; const int M1_dir2 = 52; const int pwm1= 2; const int M2_dir1 = 40; const int M2_dir2 = 42; const int pwm2= 4; void setup() { // initialize serial: Serial.begin(9600); // make the pins outputs: pinMode(M1_dir1, OUTPUT); pinMode(M1_dir2, OUTPUT); pinMode(pwm1, OUTPUT); pinMode(M2_dir1, OUTPUT); pinMode(M2_dir2, OUTPUT); pinMode(pwm2, OUTPUT); pinMode(sensor1, INPUT); pinMode(sensor2, INPUT); pinMode(sensor3, INPUT); } void loop() { //read sensor values readSensor(); //generate states for each sensor right = generatestates(sensor1Value); //A0 == Sensor1 //Left is A0 left = generatestates(sensor2Value); //A1 == Sensor1 //Front is A1 front = generatestates(sensor3Value); //A2 == Sensor1 //Right is A2 //Print Sensor Values //Serial.print("left:"); //Serial.print(left); //Serial.print(" "); //Serial.print("front:"); //Serial.print(front); //Serial.print(" "); //Serial.print("right:"); //Serial.println(right); //decision making module decide_motion(); //Keyboard Control of Motors while (Serial.available() > 0) //while user gives input { c = Serial.read(); //read user input if (c == 'A') //turn left //Keyboard input A { turn('l', 200); } else if(c == 'W') //forward //Keyboard input W { forward(250); } else if(c == 'D') //turn right //Keyboard input D { turn('r', 200); } else if(c == 'X') //backward //Keyboard input X { backward(250); } else if(c == 'S') //backward //Keyboard input X { runMotor1(0); runMotor2(0); } } //end of while } //end of main loop //*******************************************************// //function to run motor 1 void runMotor1(int speed_M1) { if (speed_M1 > 0) //move forward { digitalWrite(M1_dir1, HIGH); digitalWrite(M1_dir2, LOW); analogWrite(pwm1, 255-speed_M1); } else if(speed_M1 < 0) //move backward { digitalWrite(M1_dir1, LOW); digitalWrite(M1_dir2, HIGH); analogWrite(pwm1, 255+speed_M1); } else if(speed_M1 == 0) { digitalWrite(M1_dir1, LOW); digitalWrite(M1_dir2, LOW); analogWrite(pwm1, speed_M1); } } //end of function to run motor 1 //*******************************************************// //function to run motor 2 void runMotor2(int speed_M2) { if (speed_M2 > 0) //move forward { digitalWrite(M2_dir1, LOW); digitalWrite(M2_dir2, HIGH); analogWrite(pwm2, 255 - speed_M2); } else if(speed_M2 < 0) //move backward { digitalWrite(M2_dir1, HIGH); digitalWrite(M2_dir2, LOW); analogWrite(pwm2, 255 + speed_M2); } else if(speed_M2 == 0) { digitalWrite(M2_dir1, LOW); digitalWrite(M2_dir2, LOW); analogWrite(pwm2, speed_M2); } } //end of function to run motor 2 //*******************************************************// //function to turn left or right void turn(char direction, int sharpness) { if( direction == 'l') //turn left { runMotor1(speed + sharpness); runMotor2(speed - sharpness); } else if( direction == 'r') //turn right { runMotor1(speed - sharpness); runMotor2(speed + sharpness); } } //end of function to turn //*******************************************************// ////function to read Sensor Values //void readSensor() //{ // new_sensor1Value = analogRead(sensor1); //Sensor Inputs // new_sensor2Value = analogRead(sensor2); // new_sensor3Value = analogRead(sensor3); // // //complimentary filter // sensor1Value = (0.8*sensor1Value) + (0.2* new_sensor1Value); // sensor2Value = (0.8*sensor2Value) + (0.2* new_sensor2Value); // sensor3Value = (0.8*sensor3Value) + (0.2* new_sensor3Value); // // //printing sensor values // //Serial.println(sensor1Value); // //Serial.println(sensor2Value); // //Serial.println(sensor3Value); // // //} ////end of read sensor function ////*******************************************************// //imdl //function to read Sensor Values void readSensor() { sensor1Value = analogRead(sensor1); //Sensor Inputs //sensor2Value = analogRead(sensor2); sensor3Value = analogRead(sensor3); // //complimentary filter // sensor1Value = (0.8*sensor1Value) + (0.2* new_sensor1Value); // sensor2Value = (0.8*sensor2Value) + (0.2* new_sensor2Value); // sensor3Value = (0.8*sensor3Value) + (0.2* new_sensor3Value); // //printing sensor values Serial.print(sensor1Value); Serial.print(" "); //Serial.print(sensor2Value); Serial.println(sensor3Value); // } //end of read sensor function //*******************************************************// // ////function to generate states from sensor readings //int generatestates(float sensorvalue) //{ // if (sensorvalue >= 450) //State STOP denoted by value 0 // state = 0; // else if ((450 < sensorvalue) && (sensorvalue >= 350)) //State CLOSE denoted by value 1 // state = 1; // else if ((350 < sensorvalue) && (sensorvalue >= 320)) //State APPROACHING CLOSE denoted by value 2 // state = 2; // else if ((sensorvalue < 320)) //State FAR denoted by value 3 // state = 3; // // return state; //} ////end of generate states function ////*******************************************************// //function to move forward void forward(int fwd_speed) { runMotor1(fwd_speed); runMotor2(fwd_speed); } //end of forward function //*******************************************************// void backward(int bck_speed) { runMotor1(-bck_speed); runMotor2(-bck_speed); } //end of backward function //*******************************************************// void stop(int stp_speed) { runMotor1(0); runMotor2(0); } //end of stop function //*******************************************************// //function to decide motion //void decide_motion() //{ // if ((left == 0) && (front == 0) && (right == 0)) // { // backward(200); // //stop(0); // } // else if ((left == 3) && (front == 3) && (right == 3)) // { // forward(max_speed); // } // else if ((left == 3) && ((right == 1) || (right == 2) || (right == 0))) // { // turn('l',220); // } // else if ((right == 3) && ((left == 1) || (left == 2) || (left == 0))) // { // turn('r',220); // } // else if ((front == 1) || (front == 2)) // { // forward(reduced_speed); // } //} ////end of function to decide motion ////*******************************************************// //void decide_motion() //{ // if ((left == 0) && (right == 0)) // { // backward(255); // turn('l',255); // delay(800); // } // else if ((left == 3) && (right == 3)) // { // forward(max_speed); // } // else if ((right == 3) && ((left == 1) || (left == 0) || (left == 2))) // { // turn('r',255); // delay(800); // } // else if ((left == 3) && ((right == 1) || (right == 0)) || (right == 2)) // { // turn('l',255); // delay(800); // } // else if (((left == 2) && (right == 2))) // { // forward(175); // } // else if (((left == 1) && (right == 1))) // { // backward(255); // turn('l',255); // delay(800); // } //} // //imdl //obstacle avoidance void decide_motion() { if ((left == 0) && (right == 0)) //00 //backward { backward(255); turn('l',255); turn('l',255); delay(800); } else if ((left == 0) && (right == 1)) //01 //right { turn('r', 255); delay(100); turn('r', 255); delay(100); } else if ((left == 1) && (right == 0)) //10 //left { turn('l',255); delay(100); turn('l',255); delay(100); } else if ((left == 1) && (right == 1)) //11 //forward { forward(255); } } //imdl //function to generate states from sensor readings int generatestates(float sensorvalue) { if (sensorvalue >= 350) //0 == object detected state = 0; else if ((sensorvalue < 350)) //1 == object not detected state = 1; return state; } //end of generate states function //*******************************************************//
[ "you@example.com" ]
you@example.com