void UICheats::addRawCode( int t, const QString& a, const QString& v, const QString& d ) { // need check in list if already is code bool b; quint32 u; // check address u = a.toUInt( &b, 16 ); if ( !b ) { CommonDialogs::information( QtYabause::translate( "Invalid Address" ) ); return; } // check value u = v.toUInt( &b, 16 ); if ( !b ) { CommonDialogs::information( QtYabause::translate( "Invalid Value" ) ); return; } // add value if ( CheatAddCode( t, a.toUInt(NULL, 16), v.toUInt() ) != 0 ) { CommonDialogs::information( QtYabause::translate( "Unable to add code" ) ); return; } // get cheats and cheats count int cheatsCount; mCheats = CheatGetList( &cheatsCount ); // change description if ( CheatChangeDescriptionByIndex( cheatsCount -1, d.toLatin1().data() ) != 0 ) CommonDialogs::information( QtYabause::translate( "Unable to change description" ) ); // add code in treewidget addCode( cheatsCount -1 ); }
void Lingo::runTests() { Common::File inFile; Common::ArchiveMemberList fileList; SearchMan.listMatchingMembers(fileList, "*.lingo"); int counter = 1; for (Common::ArchiveMemberList::iterator it = fileList.begin(); it != fileList.end(); ++it) { Common::ArchiveMember const &m = **it; Common::SeekableReadStream *const stream = m.createReadStream(); if (stream) { uint size = stream->size(); char *script = (char *)calloc(size + 1, 1); stream->read(script, size); warning("Compiling file %s of size %d, id: %d", m.getName().c_str(), size, counter); _hadError = false; addCode(script, kMovieScript, counter); if (!_hadError) executeScript(kMovieScript, counter); else warning("Skipping execution"); free(script); counter++; } inFile.close(); } }
bool Context::compileScript(const std::string &file) { std::string scriptCode; // Deal with file contents { FILE *scriptFile = fopen(file.c_str(), "rb"); if(scriptFile == 0) { std::cout << "Failed to open script" << std::endl; return false; } fseek(scriptFile, 0, SEEK_END); const std::size_t fileLength = ftell(scriptFile); fseek(scriptFile, 0, SEEK_SET); scriptCode.resize(fileLength); const std::size_t c = fread(&scriptCode[0], fileLength, 1, scriptFile); if(c == 0) { std::cout << "Failed to load script" << std::endl; return false; } } return addCode(scriptCode, file); }
/** * LZW main compress function * @param s LZW state * @param inbuf Input buffer * @param insize Size of input buffer * @return Number of bytes written or -1 on error */ int ff_lzw_encode(LZWEncodeState *s, const uint8_t *inbuf, int insize) { int i; if(insize * 3 > (s->bufsize - s->output_bytes) * 2) { return -1; } if (s->last_code == LZW_PREFIX_EMPTY) clearTable(s); for (i = 0; i < insize; i++) { uint8_t c = *inbuf++; int code = findCode(s, c, s->last_code); if (s->tab[code].hash_prefix == LZW_PREFIX_FREE) { writeCode(s, s->last_code); addCode(s, c, s->last_code, code); code = hash(0, c); } s->last_code = s->tab[code].code; if (s->tabsize >= s->maxcode - 1) { clearTable(s); } } return writtenBytes(s); }
void Programme::addCodeInstance(std::string var) { int k = indexOfVar(variables, var); if(k >= 0) { addCode(variables[k].instancier()); } else { throw "La variable \"" + var + "\" n'existe pas dans le programme \""+nom+"\"."; } }
void FontExportSerializer::generateFontManualXml(MyGUI::xml::ElementPtr _root, const MyGUI::UString& _folderName, DataPtr _data) { MyGUI::IFont* resource = MyGUI::FontManager::getInstance().getByName(_data->getPropertyValue("FontName")); MyGUI::ResourceTrueTypeFont* font = resource != nullptr ? resource->castType<MyGUI::ResourceTrueTypeFont>(false) : nullptr; if (font != nullptr) { std::string textureName = _data->getPropertyValue("Name") + ".png"; MyGUI::ITexture* texture = font->getTextureFont(); if (texture == nullptr) return; texture->saveToFile(MyGUI::UString(common::concatenatePath(_folderName, MyGUI::UString(textureName))).asUTF8()); MyGUI::xml::ElementPtr node = _root->createChild("Resource"); node->addAttribute("type", "ResourceManualFont"); node->addAttribute("name", _data->getPropertyValue("Name")); addProperty(node, "Source", textureName); addProperty(node, "SourceSize", MyGUI::IntSize(texture->getWidth(), texture->getHeight())); addProperty(node, "DefaultHeight", font->getDefaultHeight()); MyGUI::xml::Element* codes = node->createChild("Codes"); std::vector<std::pair<MyGUI::Char, MyGUI::Char> > codePointRanges = font->getCodePointRanges(); MyGUI::Char substituteCodePoint = font->getSubstituteCodePoint(); bool isCustomSubstituteCodePoint = substituteCodePoint != MyGUI::FontCodeType::NotDefined; // Add all of the code points. Skip over the substitute code point -- unless it's been customized, in which case it // needs to be added here as a regular code point and then at the end as a substitute code point. for (std::vector<std::pair<MyGUI::Char, MyGUI::Char> >::const_iterator iter = codePointRanges.begin() ; iter != codePointRanges.end(); ++iter) for (MyGUI::Char code = iter->first; code <= iter->second && code >= iter->first; ++code) if (code != substituteCodePoint || isCustomSubstituteCodePoint) addCode(codes, code, font, false); // Always add the substitute code point last, even if it isn't the last one in the range. addCode(codes, substituteCodePoint, font, true); } }
ColorCodes::ColorCodes() { addCode(eCOLOR_RED, "red"); addCode(eCOLOR_GREEN, "green"); addCode(eCOLOR_BLUE, "blue"); addCode(eCOLOR_YELLOW, "yellow"); addCode(eCOLOR_ORANGE, "orange"); addCode(eCOLOR_BROWN, "brown"); addCode(eCOLOR_BLACK, "black"); addCode(eCOLOR_WHITE, "white"); addCode(eCOLOR_GREY, "grey"); }
LocationCodes::LocationCodes() { addCode(eLOCATION_OVER, "over"); addCode(eLOCATION_UNDER, "under"); addCode(eLOCATION_LEFT_TO, "left to"); addCode(eLOCATION_RIGHT_TO, "right to"); addCode(eLOCATION_INFRONT, "in front of"); addCode(eLOCATION_BEHIND, "behind"); addCode(eLOCATION_INSIDE, "inside"); addCode(eLOCATION_OUTSIDE, "outside"); }
void UICheats::addARCode( const QString& c, const QString& d ) { // need check in list if already is code // add code if ( CheatAddARCode( c.toLatin1().constData() ) != 0 ) { CommonDialogs::information( QtYabause::translate( "Unable to add code" ) ); return; } // change the description int cheatsCount; mCheats = CheatGetList( &cheatsCount ); if ( CheatChangeDescriptionByIndex( cheatsCount -1, d.toLatin1().data() ) != 0 ) CommonDialogs::information( QtYabause::translate( "Unable to change description" ) ); // add code in treewidget addCode( cheatsCount -1 ); }
UICheats::UICheats( QWidget* p ) : QDialog( p ) { // set up dialog setupUi( this ); if ( p && !p->isFullScreen() ) setWindowFlags( Qt::Sheet ); // cheat counts int cheatsCount; // get cheats mCheats = CheatGetList( &cheatsCount ); // add know cheats to treewidget for ( int id = 0; id < cheatsCount; id++ ) addCode( id ); // set save button state pbSaveFile->setEnabled( cheatsCount ); // retranslate widgets QtYabause::retranslateWidget( this ); }
void UICheats::on_pbLoadFile_clicked() { const QString s = CommonDialogs::getOpenFileName( ".", QtYabause::translate( "Choose a cheat file to open" ), QtYabause::translate( "Yabause Cheat Files (*.yct);;All Files (*)" ) ); if ( !s.isEmpty() ) { if ( CheatLoad( s.toLatin1().constData() ) == 0 ) { // clear tree twCheats->clear(); // get cheats and cheats count int cheatsCount; mCheats = CheatGetList( &cheatsCount ); // add cheats for ( int i = 0; i < cheatsCount; i++ ) addCode( i ); } else CommonDialogs::information( QtYabause::translate( "Unable to open file for saving" ) ); } }
void Lingo::runTests() { Common::File inFile; Common::ArchiveMemberList fsList; SearchMan.listMatchingMembers(fsList, "*.lingo"); Common::StringArray fileList; int counter = 1; for (Common::ArchiveMemberList::iterator it = fsList.begin(); it != fsList.end(); ++it) fileList.push_back((*it)->getName()); Common::sort(fileList.begin(), fileList.end()); for (uint i = 0; i < fileList.size(); i++) { Common::SeekableReadStream *const stream = SearchMan.createReadStreamForMember(fileList[i]); if (stream) { uint size = stream->size(); char *script = (char *)calloc(size + 1, 1); stream->read(script, size); debugC(2, kDebugLingoCompile, "Compiling file %s of size %d, id: %d", fileList[i].c_str(), size, counter); _hadError = false; addCode(script, kMovieScript, counter); if (!_hadError) executeScript(kMovieScript, counter); else debugC(2, kDebugLingoCompile, "Skipping execution"); free(script); counter++; } inFile.close(); } }
void Shader::add( std::string fileName, GLenum type ) { try { if ( _shaderProgram == 0 ) _shaderProgram = glCreateProgram(); if (_shaderProgram == 0) throw (ShaderException("can't create shader program")); std::string code = addCode(fileName); GLuint object = compileShader(code, type); _shaderObjects.insert(std::pair<GLenum, GLuint>(type, object)); // Bind the shader to the program. glAttachShader(_shaderProgram, object); } catch (ShaderException e) { std::cerr << e.what() << std::endl; exit(1); } catch (std::exception & e) { std::cout << e.what() << std::endl; } catch (...) { std::cerr << "WTF" << std::endl; } }
void FontPanel::generateFontManualXml(MyGUI::xml::ElementPtr _root, const std::string& _textureName, const std::string& _fontName) { _root->addAttribute("type", "Resource"); _root->addAttribute("version", "1.1"); MyGUI::xml::ElementPtr node = _root->createChild("Resource"); node->addAttribute("type", "ResourceManualFont"); node->addAttribute("name", _fontName); addProperty(node, "Source", _textureName); addProperty(node, "DefaultHeight", mFontHeight); MyGUI::IFont* font = MyGUI::FontManager::getInstance().getByName(mFontName); MyGUI::xml::Element* codes = node->createChild("Codes"); addCode(codes, MyGUI::FontCodeType::Cursor, font); addCode(codes, MyGUI::FontCodeType::Selected, font); addCode(codes, MyGUI::FontCodeType::SelectedBack, font); addCode(codes, 32, font); addCode(codes, 9, font); MyGUI::IntSize range1 = MyGUI::IntSize::parse(mEditRange1->getOnlyText()); MyGUI::IntSize range2 = MyGUI::IntSize::parse(mEditRange2->getOnlyText()); MyGUI::IntSize hide1 = MyGUI::IntSize::parse(mEditHide->getOnlyText()); for (int index = range1.width; index <= range1.height; ++ index) { if (index < hide1.width || index > hide1.height) addCode(codes, index, font); } for (int index = range2.width; index <= range2.height; ++ index) { if (index < hide1.width || index > hide1.height) addCode(codes, index, font); } }
int testmain() { Object *root = CreateObject("Undefined", "Undefined", 0, CodeBlock, "int"); Object *basetype = CreateObject("BaseType", "BaseType", 0, Type, 0); Object *rect = CreateObject("Rectangle", "BaseType_Rectangle", basetype, Type, 0); Object *rectConst = CreateObject("Rectangle", "Rectangle_Rectangle_Rectangle_int_int", 0, Constructor, "Rectangle"); Object *subexpr = CreateObject(0, 0, 0, Expression, "float"); addCode(subexpr, "3.14159"); addParam(rectConst, "int"); addParam(rectConst, "int"); addSymbol(rectConst, CreateObject("width", "width", 0, Variable, "int")); addSymbol(rectConst, CreateObject("height", "height", 0, Variable, "int")); addSymbol(rectConst, CreateObject("self", "self", 0, Variable, "Rectangle*")); addCode(rectConst, "Rectangle * Rectangle_Rectangle_Rectangle_int_int(int width, int height) {"); addCode(rectConst, " Rectangle * self = (Rectangle*)malloc(sizeof(Rectangle));"); addCode(rectConst, " self->w = width;"); addCode(rectConst, " self->h = height;"); addCode(rectConst, " return self;"); addCode(rectConst, "}"); addSymbol(rect, CreateObject("w", "w", 0, Variable, "int")); addSymbol(rect, CreateObject("h", "h", 0, Variable, "int")); addSymbol(rect, rectConst); addCode(rect, "typedef struct {"); addCode(rect, " BaseType parent;"); addCode(rect, " int w;"); addCode(rect, " int h;"); addCode(rect, "} Rectangle;"); addSymbol(root, basetype); addSymbol(root, rect); addSymbol(root, subexpr); printTree(root, 0); return 0; }
static int recordCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo * outTime, PaStreamCallbackFlags status, void *userData) { paTestData *data = (paTestData *) userData; SAMPLE *rptr = (SAMPLE *) inputBuffer; long i; SAMPLE *myPtr = rptr; unsigned int time; int diff; SAMPLE *outptr = (SAMPLE *) outputBuffer; int out; double currentSignal = data->remainingSignal; lirc_t signal; /* Prevent unused variable warnings. */ (void)outTime; if (status & paOutputUnderflow) logprintf(LOG_WARNING, "Output underflow %s", hw.device); if (status & paInputOverflow) logprintf(LOG_WARNING, "Input overflow %s", hw.device); for (i = 0; i < framesPerBuffer; i++, myPtr++) { /* check if we have to ignore this sample */ if (data->samplesToIgnore) { *myPtr = 128; data->samplesToIgnore--; } /* New Algo */ diff = abs(data->lastFrames[0] - *myPtr); if (diff > 100) { if (data->pulseSign == 0) { /* we got the first signal, this is a PULSE */ if (*myPtr > data->lastFrames[0]) { data->pulseSign = 1; } else { data->pulseSign = -1; } } if (data->lastCount > 0) { if (*myPtr > data->lastFrames[0] && data->lastSign <= 0) { /* printf("CHANGE ++ "); */ data->lastSign = 1; time = data->lastCount * 1000000 / data->samplerate; if (data->lastSign == data->pulseSign) { addCode(time); /* printf("Pause: %d us, %d \n", time, data->lastCount); */ } else { addCode(time | PULSE_BIT); /* printf("Pulse: %d us, %d \n", time, data->lastCount); */ } data->lastCount = 0; } else if (*myPtr < data->lastFrames[0] && data->lastSign >= 0) { /* printf("CHANGE -- "); */ data->lastSign = -1; time = data->lastCount * 1000000 / data->samplerate; if (data->lastSign == data->pulseSign) { /* printf("Pause: %d us, %d \n", time, data->lastCount); */ addCode(time); } else { /* printf("Pulse: %d us, %d \n", time, data->lastCount); */ addCode(time | PULSE_BIT); } data->lastCount = 0; } } } if (data->lastCount < 100000) { data->lastCount++; } data->lastFrames[0] = data->lastFrames[1]; data->lastFrames[1] = *myPtr; /* skip 2. channel */ if (NUM_CHANNELS == 2) myPtr++; } /* generate output */ for (i = 0; i < framesPerBuffer; i++) { if (currentSignal <= 0.0) { /* last signal we sent went out */ /* try to read a new signal, non blocking */ if (read(sendPipe[0], &signal, sizeof(signal)) > 0) { if (data->signaledDone) { /* first one sent is the carrier frequency */ data->carrierFreq = signal; data->signaledDone = 0; } else { /* when a new signal is read, add it */ currentSignal += signal; /* invert the phase */ data->signalPhase = data->signalPhase ? 0 : 1; } /* when transmitting, ignore input samples for one second */ data->samplesToIgnore = data->samplerate; } else { /* no more signals, reset phase */ data->signalPhase = 0; /* signal that we have written all signals */ if (!data->signaledDone) { char done = 0; data->signaledDone = 1; (void)write(completedPipe[1], &done, sizeof(done)); } } } if (currentSignal > 0.0) { if (data->signalPhase) { /* write carrier */ out = rint(sin(data->carrierPos / (180.0 / PI)) * 127.0 + 128.0); } else { out = 128; } /* one channel is inverted, so both channels can be used to double the voltage */ *outptr++ = out; if (NUM_CHANNELS == 2) *outptr++ = 256 - out; /* subtract how much of the current signal was sent */ currentSignal -= 1000000.0 / data->samplerate; } else { *outptr++ = 128; if (NUM_CHANNELS == 2) *outptr++ = 128; } /* increase carrier position */ /* carrier frequency is halved */ data->carrierPos += (double)data->carrierFreq / data->samplerate * 360.0 / 2.0; if (data->carrierPos >= 360.0) data->carrierPos -= 360.0; } /* save how much we still have to write */ data->remainingSignal = currentSignal; return 0; }
const char *Operation::buildCode(CodeType type) { if ( codebuf ) { codebuf[0]=0; freeSize=bufSize; } addCode(header1[type]); if (needsRandom || needsNoise ) { switch(type) { case(C) : addCode(format("TCOD_random_t rnd=NULL;\n",seed)); break; case(CPP) : addCode(format("TCODRandom *rnd=new TCODRandom(%uU);\n",seed)); break; case(PY) : addCode(format("rnd=libtcod.random_new_from_seed(%u)\n",seed)); break; default:break; } } if (needsNoise ) { switch(type) { case(C) : addCode("TCOD_noise_t noise=NULL;\n"); break; case(CPP) : addCode("TCODNoise *noise=new TCODNoise(2,rnd);\n"); break; case(PY) : addCode("noise=libtcod.noise_new(2,libtcod.NOISE_DEFAULT_HURST,libtcod.NOISE_DEFAULT_LACUNARITY,rnd)\n"); break; default:break; } } for (const char **s=initCode[type].begin(); s!=initCode[type].end(); s++) { addCode(*s); } addCode(header2[type]); for (Operation **op=list.begin(); op!=list.end(); op++) { const char *code=(*op)->getCode(type); addCode(code); } addCode(footer1[type]); if ((needsRandom || needsNoise) && type == C ) { addCode(format("\trnd=TCOD_random_new_from_seed(%uU);\n",seed)); if (needsNoise) { addCode("\tnoise=TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST,TCOD_NOISE_DEFAULT_LACUNARITY,rnd);\n"); } } addCode(footer2[type]); return codebuf; }
CExpression& CExpression::rebild(const char* CExpression) { delete[] walkthroughArray; delete[] numArray; walkthroughArray = 0; numArray = 0; fine = true; if (!isExp(CExpression)) { fine = false; return *this; } int len = static_cast<int>(strlen(CExpression)); char* sourseString = new char[len * 3 + 1]; for (int i = 0, j = 0; i < len; ++i) sourseString[j++] = CExpression[i]; sourseString[len] = 0; sintAdaptation(sourseString);//Делает строку регистронезависимой, удаляет пробелы/'\t'/'\n', приводит скобочки к однообразию addCode(sourseString);//Заменяет ссылки на функции символами от -128 для удобства дальнейшего анализа std::cout << sourseString << std::endl; for (int i(0); sourseString[i]; ++i) { if (sourseString[i] == 't') sourseString[i] = 'y'; } std::cout << sourseString << std::endl; if (expForm) { toExpForm(sourseString);//Преобразовывает записи типа -3.0e-2 так, }//чтобы они вычислялись как экспоненциальная форма числа. addMult(sourseString);//Добавляет * и 0 для реализации унарного минуса. Функции объеденены по историческим причинам. sortPoland(setArray(sourseString));/*При вызове преобразует строку в массив sintElem и высылает его для сортировки в польскую нотацию*/ short i = 0, numbersCount = 0, opCount = 1; while (walkthroughArray[i].lexeme != 127) { if (walkthroughArray[i].lexeme == 'x' || walkthroughArray[i].lexeme == 'y' || !walkthroughArray[i].lexeme) { ++numbersCount;//Посчитать максимально возможное количество чисел в стеке(тоесть все числа вобще) } else { opCount += !isUnary(walkthroughArray[i].lexeme); } ++i; } //qDebug() << opCount << '<' << numbersCount; if (opCount > numbersCount) { delete[] walkthroughArray; delete[] numArray; walkthroughArray = 0; numArray = 0; fine = false; return *this; } numArray = new double[numbersCount + 1];//1 лишний элемент нужен для оптимизации алгаритма вычисления //std::cout << "объект создан.\n"; return *this; }
bool CExpression::isExp(const char* St) { /* Проверяет, является ли строка выражением. работает ощутимо долго. (но не слишком. Но сопоставимо с полным разбором строки и переводом её в выражение) */ if (!strlen(St)) { return false; } int i = -1, j = 0; char* st = new char [strlen(St) * 2]; while(St[++i])//Проверка на наличие посторонних символов if(St[i] != ' ' && St[i] != '\n') { if(St[i] >= 'A' && St[i] <= 'Z') st[j++] = St[i] - ('A' - 'a'); else if(isLetter(St[i]) || isNumber(St[i]) || St[i] == '*' || St[i] == '/' || St[i] == '+' || St[i] == '-' || St[i] == '^' || St[i] == '(' || St[i] == ')' || St[i] == ',' || St[i] == '.') st[j++] = St[i]; else if(St[i] == '}' || St[i] == ']') st[j++] = ')'; else if(St[i] == '{' || St[i] == '[') st[j++] = '('; else { delete[] st; return !true && !false; } } i = -1; while(st[++i]) if(st[i] == 'p' && st[i + 1] == 'i')//Если это pi, заменить его на 77, чтобы в дальнейшем анализировать как число { st[i] = '7'; st[++i] = '7'; } else if(st[i] == 'e' || st[i] == 'x' || st[i] =='y' || st[i] == 't' )//если это e, y или x st[i] = '2'; st[j] = i = 0; //std::cout << "Symbols is right.\nFree string is \"" << st << "\"\n"; if(*st != 0 && ( *st != '+' && *st != '-' && *st != '(' && !isNumber(*st) && !isLetter(*st) ) )//Проверка на порядок следования { delete[] st; return !true && !false; } //std::cout << "First symbol is right.\n"; while(st[++i]) if( (( st[i] == '+' || st[i] == '-' || st[i] == '/' || st[i] == '*' || st[i] == '^' || st[i] == '(' || st[i] == ',' ) && !isNumber(st[i + 1]) && !isLetter(st[i + 1]) && st[i + 1] != '(' && st[i + 1] != '-' && st[i + 1] != '+') || (st[i] == ')' && !isNumber(st[i + 1]) && !isLetter(st[i + 1]) && st[i + 1] != '(' && st[i + 1] != '-' && st[i + 1] != '+' && st[i + 1] != '^' && st[i + 1] != ')' && st[i + 1] != '*' && st[i + 1] != '/' && st[i + 1] != ',' && st[i + 1]) || (isLetter(st[i]) && ( !st[i + 1] || (!isLetter(st[i + 1]) && st[i + 1] != '(' )))) { //std::cout << i << " is " << st[i] << '\n'; delete[] st; return !true && !false; } //Тест последнего символа --i; if(st[i] != ')' && ( st[i] < '0' || st[i] > '9' ) ) { delete[] st; return !true && !false; } //std::cout << "Sequence is right.\n"; //qDebug() << "()..."; i = -1; j = 0; while(st[++i])//Проверка на скобочки { if(st[i] == '(') ++j; else if(st[i] == ')') --j; if( j < 0 ) { delete[] st; return !true && !false; } } if(j) { delete[] st; return !true && !false; } //std::cout << "Brackets is right.\n"; //qDebug() << "funk..."; addCode(st); i = -1; while(st[++i]) { if(isLetter(st[i]) || (i && st[i - 1] < -100 && st[i] < -100)) {//Если есть неопознанные функции - символы не заменённые на экваваленты или две функции подрят //std::cout << st << std::endl; delete[] st; return !true && !false; } } //qDebug() << "true"; delete[] st; return true; }