DAT2::DAT2(VFS* vfs, const std::string& file) : VFSSource(vfs), m_datpath(file), m_data(vfs->open(file)), m_filelist() { FL_LOG(_log, LMsg("MFFalloutDAT2") << "loading: " << file << " filesize: " << m_data->getDataLength()); m_data->setIndex(m_data->getDataLength() - 8); uint32_t fileListLength = m_data->read32Little(); uint32_t archiveSize = m_data->read32Little(); FL_LOG(_log, LMsg("MFFalloutDAT2") << "FileListLength: " << fileListLength << " ArchiveSize: " << archiveSize); if (archiveSize != m_data->getDataLength()) throw InvalidFormat("size mismatch"); m_data->setIndex( archiveSize - fileListLength - 8); m_filecount = m_data->read32Little(); m_currentIndex = m_data->getCurrentIndex(); FL_LOG(_log, LMsg("MFFalloutDAT2 FileCount: ") << m_filecount); // Do not read the complete file list at startup. // Instead read a chunk each frame. m_timer.setInterval(0); m_timer.setCallback( boost::bind( &DAT2::readFileEntry, this) ); m_timer.start(); }
void StrOp::main(int argc, char** argv) { std::string x = "Esto es= que y=o diga t=d=o= sin ='s =D"; FL_LOG(x); FindReplace(x,"="," = "); FL_LOG(x); }
void Engine::destroy() { FL_LOG(_log, "Destructing engine"); delete m_cursor; delete m_view; delete m_model; delete m_soundmanager; delete m_guimanager; delete m_gui_graphics; // Note the dependancy between image and animation pools // as animations reference images they have to be deleted // before clearing the image pool. delete m_animpool; delete m_imagepool; delete m_eventmanager; m_renderbackend->deinit(); delete m_renderbackend; delete m_vfs; delete m_timemanager; TTF_Quit(); SDL_Quit(); #ifdef USE_COCOA objc_msgSend(m_autoreleasePool, sel_registerName("release")); #endif FL_LOG(_log, "================== Engine destructed =================="); m_destroyed = true; //delete m_logmanager; }
void Test::SimpleMamdani() { FuzzyOperator& op = FuzzyOperator::DefaultFuzzyOperator(); FuzzyEngine engine("simple-mamdani", op); engine.hedgeSet().add(new fl::HedgeNot); engine.hedgeSet().add(new fl::HedgeSomewhat); engine.hedgeSet().add(new fl::HedgeVery); fl::InputLVar* energy = new fl::InputLVar("Energy"); energy->addTerm(new fl::ShoulderTerm("LOW", 0.25, 0.5, true)); energy->addTerm(new fl::TriangularTerm("MEDIUM", 0.25, 0.75)); energy->addTerm(new fl::ShoulderTerm("HIGH", 0.50, 0.75, false)); engine.addInputLVar(energy); fl::OutputLVar* health = new fl::OutputLVar("Health"); health->addTerm(new fl::TriangularTerm("BAD", 0.0, 0.50)); health->addTerm(new fl::TriangularTerm("REGULAR", 0.25, 0.75)); health->addTerm(new fl::TriangularTerm("GOOD", 0.50, 1.00)); engine.addOutputLVar(health); fl::RuleBlock* block = new fl::RuleBlock(); block->addRule(new fl::MamdaniRule("if Energy is LOW then Health is BAD", engine)); block->addRule(new fl::MamdaniRule("if Energy is MEDIUM then Health is REGULAR", engine)); block->addRule(new fl::MamdaniRule("if Energy is HIGH then Health is GOOD", engine)); engine.addRuleBlock(block); for (fl::flScalar in = 0.0; in < 1.1; in += 0.1) { energy->setInput(in); engine.process(); fl::flScalar out = health->output().defuzzify(); (void)out; //Just to avoid warning when building FL_LOG("Energy=" << in); FL_LOG("Energy is " << energy->fuzzify(in)); FL_LOG("Health=" << out); FL_LOG("Health is " << health->fuzzify(out)); FL_LOG("--"); } }
DAT1::DAT1(VFS* vfs, const std::string& file) : VFSSource(vfs), m_datpath(file), m_data(vfs->open(file)) { FL_LOG(_log, LMsg("MFFalloutDAT1") << "loading: " << file << " filesize: " << m_data->getDataLength()); m_data->setIndex(0); const uint32_t dircount = m_data->read32Big(); m_data->moveIndex(4*3); FL_LOG(_log, LMsg("MFFalloutDAT1") << "number of directories " << dircount); // Sanity check. Each dir entry needs min. 16 bytes. if( dircount*16 > m_data->getDataLength() ) { throw InvalidFormat("directory count larger than filesize."); } std::list<std::string> dir_names; for (uint32_t i = 0; i < dircount; ++i) { std::string name = readString(); if (name == ".") { name = ""; } dir_names.push_back(name); } for(std::list<std::string>::iterator i= dir_names.begin(); i!= dir_names.end(); ++i) loadFileList(*i); }
void Test::SimpleTakagiSugeno() { FuzzyOperator& op = FuzzyOperator::DefaultFuzzyOperator(); op.setDefuzzifier(new TakagiSugenoDefuzzifier); FuzzyEngine engine("takagi-sugeno", op); fl::InputLVar* x = new fl::InputLVar("x"); x->addTerm(new fl::TriangularTerm("NEAR_1", 0, 2)); x->addTerm(new fl::TriangularTerm("NEAR_2", 1, 3)); x->addTerm(new fl::TriangularTerm("NEAR_3", 2, 4)); x->addTerm(new fl::TriangularTerm("NEAR_4", 3, 5)); x->addTerm(new fl::TriangularTerm("NEAR_5", 4, 6)); x->addTerm(new fl::TriangularTerm("NEAR_6", 5, 7)); x->addTerm(new fl::TriangularTerm("NEAR_7", 6, 8)); x->addTerm(new fl::TriangularTerm("NEAR_8", 7, 9)); x->addTerm(new fl::TriangularTerm("NEAR_9", 8, 10)); engine.addInputLVar(x); fl::OutputLVar* f_x = new fl::OutputLVar("f_x"); f_x->addTerm(new fl::FunctionTerm("function", "(sin x) / x", 0, 10)); engine.addOutputLVar(f_x); fl::RuleBlock* block = new fl::RuleBlock(); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_1 then f_x=0.84", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_2 then f_x=0.45", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_3 then f_x=0.04", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_4 then f_x=-0.18", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_5 then f_x=-0.19", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_6 then f_x=-0.04", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_7 then f_x=0.09", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_8 then f_x=0.12", engine)); block->addRule(new fl::TakagiSugenoRule("if x is NEAR_9 then f_x=0.04", engine)); engine.addRuleBlock(block); int n = 40; flScalar mse = 0; for (fl::flScalar in = x->minimum(); in < x->maximum() ; in += (x->minimum() + x->maximum()) / n) { x->setInput(in); engine.process(); flScalar expected = f_x->term(0)->membership(in); flScalar obtained = f_x->output().defuzzify(); flScalar se = (expected - obtained) * (expected - obtained); mse += isnan(se) ? 0 : se; FL_LOG("x=" << in << "\texpected_out=" << expected << "\tobtained_out=" << obtained << "\tse=" << se); } FL_LOG("MSE=" << mse / n); }
void FllImporter::processRuleBlock(const std::string& block, Engine* engine) const { std::istringstream reader(block); std::string line; FL_unique_ptr<RuleBlock> ruleBlock(new RuleBlock); while (std::getline(reader, line)) { std::pair<std::string, std::string> keyValue = parseKeyValue(line, ':'); if ("RuleBlock" == keyValue.first) { ruleBlock->setName(keyValue.second); } else if ("enabled" == keyValue.first) { ruleBlock->setEnabled(parseBoolean(keyValue.second)); } else if ("conjunction" == keyValue.first) { ruleBlock->setConjunction(parseTNorm(keyValue.second)); } else if ("disjunction" == keyValue.first) { ruleBlock->setDisjunction(parseSNorm(keyValue.second)); } else if ("implication" == keyValue.first) { ruleBlock->setImplication(parseTNorm(keyValue.second)); } else if ("activation" == keyValue.first) { TNormFactory* tnorm = FactoryManager::instance()->tnorm(); //@todo remove backwards compatibility in version 7.0 if (tnorm->hasConstructor(keyValue.second)) { ruleBlock->setImplication(parseTNorm(keyValue.second)); FL_LOG("[warning] obsolete usage of identifier <activation: TNorm> " "in RuleBlock"); FL_LOG("[information] from version 6.0, the identifiers are " "<activation: Activation> for Activation methods " "and <implication: TNorm> for T-Norms"); FL_LOG("[backward compatibility] assumed " "<implication: " << keyValue.second << "> " "instead of <activation: " << keyValue.second << ">"); } else { ruleBlock->setActivation(parseActivation(keyValue.second)); } } else if ("rule" == keyValue.first) { Rule* rule = new Rule; rule->setText(keyValue.second); try { rule->load(engine); } catch (std::exception& ex) { FL_LOG(ex.what()); } ruleBlock->addRule(rule); } else { throw Exception("[import error] key <" + keyValue.first + "> not " "recognized in pair <" + keyValue.first + ":" + keyValue.second + ">", FL_AT); } } engine->addRuleBlock(ruleBlock.release()); }
scalar MeanOfMaximum::defuzzify(const Term* term, scalar minimum, scalar maximum) const { if (maximum - minimum > _resolution) { FL_LOG("[accuracy warning] the resolution <" << _resolution << "> " "is smaller than the range <" << minimum << ", " << maximum << ">. In order to " "improve the accuracy, the resolution should be at least equal to the range."); } scalar dx = (maximum - minimum) / _resolution; scalar x, y; scalar ymax = -1.0; scalar xsmallest = minimum; scalar xlargest = maximum; bool samePlateau = false; for (int i = 0; i < _resolution; ++i) { x = minimum + (i + 0.5) * dx; y = term->membership(x); if (Op::isGt(y, ymax)) { ymax = y; xsmallest = x; xlargest = x; samePlateau = true; } else if (Op::isEq(y, ymax) and samePlateau) { xlargest = x; } else if (Op::isLt(y, ymax)) { samePlateau = false; } } return (xlargest + xsmallest) / 2.0; }
scalar Bisector::defuzzify(const Term* term, scalar minimum, scalar maximum) const { if (maximum - minimum > _resolution) { FL_LOG("[accuracy warning] the resolution <" << _resolution << "> " "is smaller than the range <" << minimum << ", " << maximum << ">. In order to " "improve the accuracy, the resolution should be at least equal to the range."); } scalar dx = (maximum - minimum) / _resolution; int counter = _resolution; int left = 0, right = 0; scalar leftArea = 0, rightArea = 0; scalar xLeft = minimum, xRight = maximum; while (counter-- > 0) { if (fl::Op::isLE(leftArea, rightArea)) { xLeft = minimum + (left + 0.5) * dx; leftArea += term->membership(xLeft); left++; } else { xRight = maximum - (right + 0.5) * dx; rightArea += term->membership(xRight); right++; } } //Inverse weighted average to compensate scalar bisector = (leftArea * xRight + rightArea * xLeft) / (leftArea + rightArea); return bisector; }
void DAT2::readFileEntry() const { assert( m_filecount != 0); // Load more items per call, // otherwise it takes _ages_ until everything is in. uint32_t load_per_cycle = 50; if( load_per_cycle > m_filecount ) load_per_cycle = m_filecount; m_filecount -= load_per_cycle; // Save the old index in an exception save way. IndexSaver isaver(m_data.get()); // Move index to file list and read the entries. m_data->setIndex(m_currentIndex); RawDataDAT2::s_info info; while( load_per_cycle-- ) { uint32_t namelen = m_data->read32Little(); info.name = fixPath(m_data->readString(namelen)); info.type = m_data->read8(); info.unpackedLength = m_data->read32Little(); info.packedLength = m_data->read32Little(); info.offset = m_data->read32Little(); m_filelist.insert(std::make_pair(info.name, info)); } m_currentIndex = m_data->getCurrentIndex(); // Finally log on completion and stop the timer. if( m_filecount == 0 ) { FL_LOG(_log, LMsg("MFFalloutDAT2, All file entries in '") << m_datpath << "' loaded."); m_timer.stop(); } }
DAT2::type_filelist::const_iterator DAT2::findFileEntry(const std::string& path) const { // Either the normalization is bogus, or we have to do // it here, too. Otherwise we can't load the files returned // by listFiles. std::string name = path; // Normalize the path if (name.find("./") == 0) { name.erase(0, 2); } type_filelist::const_iterator i = m_filelist.find(name); // We might have another chance to find the file // if the number of file entries not zero. if ( m_filecount && i == m_filelist.end()) { FL_LOG(_log, LMsg("MFFalloutDAT2") << "Missing '" << name << "' in partially(" << m_filecount <<") loaded "<< m_datpath); while( m_filecount && i == m_filelist.end()) { readFileEntry(); i = m_filelist.find(name); } } return i; }
TakagiSugenoRule::TakagiSugenoRule(const std::string& rule, const FuzzyEngine& engine) : FuzzyRule() { try { parse(rule, engine); } catch (ParsingException& e) { FL_LOG(e.toString()); } }
Image* RenderBackendSDL::createMainScreen(unsigned int width, unsigned int height, unsigned char bitsPerPixel, bool fs, const std::string& title, const std::string& icon) { Uint32 flags = 0; if (fs) { flags |= SDL_FULLSCREEN; } if(icon != "") { SDL_Surface *img = IMG_Load(icon.c_str()); if(img != NULL) { SDL_WM_SetIcon(img, 0); } } SDL_Surface* screen = NULL; if( 0 == bitsPerPixel ) { /// autodetect best mode unsigned char possibleBitsPerPixel[] = {16, 24, 32, 0}; int i = 0; while( true ) { bitsPerPixel = possibleBitsPerPixel[i]; if( !bitsPerPixel ) { // Last try, sometimes VideoModeOK seems to lie. // Try bpp=0 screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( !screen ) { throw SDLException("Videomode not available"); } break; } bitsPerPixel = SDL_VideoModeOK(width, height, bitsPerPixel, flags); if ( bitsPerPixel ) { screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( screen ) { break; } } ++i; } } else { if ( !SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) { throw SDLException("Videomode not available"); } screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); } FL_LOG(_log, LMsg("RenderBackendSDL") << "Videomode " << width << "x" << height << " at " << int(screen->format->BitsPerPixel) << " bpp"); SDL_WM_SetCaption(title.c_str(), NULL); if (!screen) { throw SDLException(SDL_GetError()); } m_screen = new SDLImage(screen); return m_screen; }
void RawData::readInto(uint8_t* buffer, size_t len) { if (m_index_current + len > getDataLength()) { FL_LOG(_log, LMsg("RawData") << m_index_current << " : " << len << " : " << getDataLength()); throw IndexOverflow(__FUNCTION__); } m_datasource->readInto(buffer, m_index_current, len); m_index_current += len; }
void InfixToPostfix::main(int args, char** argv) { std::map<std::string, flScalar> m; m["x"] = 4; m["y"] = 2; m["z"] = -4; std::string x = "(sin x) / x"; FL_LOG(x); InfixToPostfix ip; ip.loadMathOperators(); std::string postfix = ip.transform(x); FL_LOG(postfix); for (flScalar x = 0.0 ; x < 10.5 ; x+=0.5){ m["x"] = x; FL_LOG(ip.evaluate(postfix, &m)); } }
bool RawData::littleEndian() { static int32_t endian = 2; if (endian == 2) { uint32_t value = 0x01; endian = reinterpret_cast<uint8_t*>(&value)[0]; FL_LOG(_log, LMsg("RawData") << "we are on a " << (endian == 1 ? "little endian" : "big endian") << " machine"); } return endian == 1; }
void FllImporter::processOutputVariable(const std::string& block, Engine* engine) const { std::istringstream reader(block); std::string line; FL_unique_ptr<OutputVariable> outputVariable(new OutputVariable); while (std::getline(reader, line)) { std::pair<std::string, std::string> keyValue = parseKeyValue(line, ':'); if ("OutputVariable" == keyValue.first) { outputVariable->setName(Op::validName(keyValue.second)); } else if ("enabled" == keyValue.first) { outputVariable->setEnabled(parseBoolean(keyValue.second)); } else if ("range" == keyValue.first) { std::pair<scalar, scalar> range = parseRange(keyValue.second); outputVariable->setRange(range.first, range.second); } else if ("default" == keyValue.first) { outputVariable->setDefaultValue(Op::toScalar(keyValue.second)); } else if ("lock-previous" == keyValue.first or "lock-valid" == keyValue.first) { outputVariable->setLockPreviousValue(parseBoolean(keyValue.second)); } else if ("lock-range" == keyValue.first) { outputVariable->setLockValueInRange(parseBoolean(keyValue.second)); } else if ("defuzzifier" == keyValue.first) { outputVariable->setDefuzzifier(parseDefuzzifier(keyValue.second)); } else if ("aggregation" == keyValue.first) { outputVariable->fuzzyOutput()->setAggregation(parseSNorm(keyValue.second)); } else if ("accumulation" == keyValue.first) { outputVariable->fuzzyOutput()->setAggregation(parseSNorm(keyValue.second)); FL_LOG("[warning] obsolete usage of identifier <accumulation: SNorm> in OutputVariable"); FL_LOG("[information] from version 6.0, the identifier <aggregation: SNorm> should be used"); FL_LOG("[backward compatibility] assumed " "<aggregation: " << keyValue.second << "> " "instead of <accumulation: " << keyValue.second << ">"); } else if ("term" == keyValue.first) { outputVariable->addTerm(parseTerm(keyValue.second, engine)); } else { throw Exception("[import error] key <" + keyValue.first + "> not " "recognized in pair <" + keyValue.first + ":" + keyValue.second + ">", FL_AT); } } engine->addOutputVariable(outputVariable.release()); }
flScalar TakagiSugenoDefuzzifier::defuzzify(const LinguisticTerm* term, int number_of_samples, const AreaCentroidAlgorithm* algorithm) const { const CompoundTerm* out = dynamic_cast<const CompoundTerm*> (term); if (!out) { FL_LOG("<CompoundTerm> expected, but <" << term->toString() << "> found." << "Takagi-Sugeno defuzzification works only on the output of Takagi-Sugeno Rules." ); return -1; } flScalar result = 0; flScalar sum_wi = 0; for (int i = 0; i < out->numberOfTerms(); ++i) { const TakagiSugenoTerm* t = dynamic_cast<const TakagiSugenoTerm*> (&out->term(i)); if (!t) { FL_LOG("<TakagiSugenoTerm> expected, but <" << out->term(i).toString() << "> found." << "Takagi-Sugeno defuzzification works only on the output of Takagi-Sugeno Rules"); return -1; } result += t->value() * t->weight(); sum_wi += t->weight(); } return result / sum_wi; }
void Test::ComplexMamdani() { FuzzyOperator& op = FuzzyOperator::DefaultFuzzyOperator(); FuzzyEngine engine("complex-mamdani", op); engine.hedgeSet().add(new fl::HedgeNot); engine.hedgeSet().add(new fl::HedgeSomewhat); engine.hedgeSet().add(new fl::HedgeVery); fl::InputLVar* energy = new fl::InputLVar("Energy"); energy->addTerm(new fl::TriangularTerm("LOW", 0.0, 0.50)); energy->addTerm(new fl::TriangularTerm("MEDIUM", 0.25, 0.75)); energy->addTerm(new fl::TriangularTerm("HIGH", 0.50, 1.00)); engine.addInputLVar(energy); fl::InputLVar* distance = new fl::InputLVar("Distance"); distance->addTerm(new fl::TriangularTerm("NEAR", 0, 500)); distance->addTerm(new fl::TriangularTerm("FAR", 250, 750)); distance->addTerm(new fl::TriangularTerm("FAR_AWAY", 500, 1000)); engine.addInputLVar(distance); fl::OutputLVar* power = new fl::OutputLVar("Power"); power->addTerm(new fl::ShoulderTerm("LOW", 0.25, 0.5, true)); power->addTerm(new fl::TriangularTerm("MEDIUM", 0.25, 0.75)); power->addTerm(new fl::ShoulderTerm("HIGH", 0.50, 0.75, false)); engine.addOutputLVar(power); fl::RuleBlock* block = new fl::RuleBlock(); block->addRule(new fl::MamdaniRule("if Energy is LOW and Distance is FAR_AWAY then Power is LOW", engine)); block->addRule(new fl::MamdaniRule("if Energy is LOW and Distance is FAR then Power is very MEDIUM", engine)); block->addRule(new fl::MamdaniRule("if Energy is LOW and Distance is NEAR then Power is HIGH", engine)); block->addRule(new fl::MamdaniRule("if Energy is MEDIUM and Distance is FAR_AWAY then Power is LOW with 0.8", engine)); block->addRule(new fl::MamdaniRule("if Energy is MEDIUM and Distance is FAR then Power is MEDIUM with 1.0", engine)); block->addRule(new fl::MamdaniRule("if Energy is MEDIUM and Distance is NEAR then Power is HIGH with 0.3", engine)); block->addRule(new fl::MamdaniRule("if Energy is HIGH and Distance is FAR_AWAY then Power is LOW with 0.43333", engine)); block->addRule(new fl::MamdaniRule("if Energy is HIGH and Distance is FAR then Power is MEDIUM", engine)); block->addRule(new fl::MamdaniRule("if Energy is HIGH and Distance is NEAR then Power is HIGH", engine)); engine.addRuleBlock(block); for (int i = 0; i < block->numberOfRules(); ++i) { FL_LOG(block->rule(i)->toString()); } return; for (fl::flScalar in = 0.0; in < 1.1; in += 0.1) { energy->setInput(in); distance->setInput(500); engine.process(); fl::flScalar out = power->output().defuzzify(); (void)out; //Just to avoid warning when building FL_LOG("Energy=" << in); FL_LOG("Energy is " << power->fuzzify(in)); FL_LOG("Health=" << out); FL_LOG("Health is " << energy->fuzzify(out)); FL_LOG("--"); } }
void Engine::destroy() { FL_LOG(_log, "Destructing engine"); delete m_cursor; delete m_model; delete m_soundmanager; delete m_guimanager; delete m_imagemanager; delete m_soundclipmanager; // delete m_eventmanager; // properly remove all the renderers created during init delete m_offrenderer; delete m_targetrenderer; std::vector<RendererBase*>::iterator rendererIter = m_renderers.begin(); for ( ; rendererIter != m_renderers.end(); ++rendererIter) { delete *rendererIter; } m_renderers.clear(); delete m_renderbackend; delete m_vfs; delete m_timemanager; TTF_Quit(); SDL_Quit(); #ifdef USE_COCOA objc_msgSend(m_autoreleasePool, sel_registerName("release")); #endif FL_LOG(_log, "================== Engine destructed =================="); m_destroyed = true; //delete m_logmanager; }
Image* RenderBackendSDL::setScreenMode(const ScreenMode& mode) { uint16_t width = mode.getWidth(); uint16_t height = mode.getHeight(); uint16_t bitsPerPixel = mode.getBPP(); bool fs = mode.isFullScreen(); uint32_t flags = mode.getSDLFlags(); SDL_Surface* screen = NULL; if (bitsPerPixel != 0) { uint16_t bpp = SDL_VideoModeOK(width, height, bitsPerPixel, flags); if (!bpp){ throw SDLException("Selected video mode not supported!"); } } screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( !screen ) { throw SDLException("Unable to set video mode selected!"); } FL_LOG(_log, LMsg("RenderBackendSDL") << "Videomode " << width << "x" << height << " at " << int(screen->format->BitsPerPixel) << " bpp"); //update the screen mode with the actual flags used m_screenMode = ScreenMode(width, height, bitsPerPixel, screen->flags); if (!screen) { throw SDLException(SDL_GetError()); } delete m_screen; m_screen = new SDLImage(screen); return m_screen; }
void Engine::preInit() { m_logmanager = LogManager::instance(); FL_LOG(_log, "================== Engine pre-init start ================="); m_timemanager = new TimeManager(); FL_LOG(_log, "Time manager created"); FL_LOG(_log, "Creating VFS"); m_vfs = new VFS(); FL_LOG(_log, "Adding root directory to VFS"); m_vfs->addSource( new VFSDirectory(m_vfs) ); m_vfs->addProvider( new DirectoryProvider() ); #ifdef HAVE_ZIP FL_LOG(_log, "Adding zip provider to VFS"); m_vfs->addProvider( new ZipProvider() ); #endif //m_vfs->addProvider(ProviderDAT2()); //m_vfs->addProvider(ProviderDAT1()); FL_LOG(_log, "Engine pre-init done"); m_destroyed = false; }
void VFS::addProvider(VFSSourceProvider* provider) { provider->setVFS(this); m_providers.push_back(provider); FL_LOG(_log, LMsg("new provider: ") << provider->getName()); }
SubImageFont::SubImageFont(const std::string& filename, const std::string& glyphs) : ImageFontBase() { FL_LOG(_log, LMsg("guichan_image_font, loading ") << filename << " glyphs " << glyphs); //prock - 504 ImagePtr img = ImageManager::instance()->load(filename); int32_t image_id = img->getHandle(); SDL_Surface* surface = img->getSurface(); m_colorkey = RenderBackend::instance()->getColorKey(); if( !surface ) { throw CannotOpenFile(filename); } // Make sure we get 32bit RGB // and copy the Pixelbuffers surface SDL_Surface *tmp = SDL_CreateRGBSurface(SDL_SWSURFACE, surface->w,surface->h,32, RMASK, GMASK, BMASK ,NULLMASK); SDL_BlitSurface(surface,0,tmp,0); surface = tmp; // Prepare the data for extracting the glyphs. uint32_t *pixels = reinterpret_cast<uint32_t*>(surface->pixels); int32_t x, w; x = 0; w=0; SDL_Rect src; src.h = surface->h; src.y = 0; uint32_t separator = pixels[0]; uint32_t colorkey = SDL_MapRGB(surface->format, m_colorkey.r, m_colorkey.g, m_colorkey.b); // if colorkey feature is not enabled then manually find the color key in the font if (!RenderBackend::instance()->isColorKeyEnabled()) { while(x < surface->w && pixels[x] == separator) { ++x; } colorkey = pixels[x]; } // Disable alpha blending, so that we use color keying SDL_SetAlpha(surface,0,255); SDL_SetColorKey(surface,SDL_SRCCOLORKEY,colorkey); FL_DBG(_log, LMsg("image_font") << " glyph separator is " << pprint(reinterpret_cast<void*>(separator)) << " transparent color is " << pprint(reinterpret_cast<void*>(colorkey))); // Finally extract all glyphs std::string::const_iterator text_it = glyphs.begin(); while(text_it != glyphs.end()) { w=0; while(x < surface->w && pixels[x] == separator) ++x; if( x == surface->w ) break; while(x + w < surface->w && pixels[x + w] != separator) ++w; src.x = x; src.w = w; tmp = SDL_CreateRGBSurface(SDL_SWSURFACE, w,surface->h,32, RMASK, GMASK, BMASK ,NULLMASK); SDL_FillRect(tmp,0,colorkey); SDL_BlitSurface(surface,&src,tmp,0); // Disable alpha blending, so that we use colorkeying SDL_SetAlpha(tmp,0,255); SDL_SetColorKey(tmp,SDL_SRCCOLORKEY,colorkey); uint32_t codepoint = utf8::next(text_it, glyphs.end()); m_glyphs[ codepoint ].surface = tmp; x += w; } // Set placeholder glyph // This should actually work ith utf8. if( m_glyphs.find('?') != m_glyphs.end() ) { m_placeholder = m_glyphs['?']; } else { m_placeholder.surface = 0; } mHeight = surface->h; SDL_FreeSurface(surface); }
void Test::main(int args, char** argv) { FL_LOG("Starting in 2 second"); FL_LOG("Example: Simple Mamdani"); FL_LOG("======================="); #ifdef _MSC_VER //Sleep(2); #else sleep(2); #endif SimpleMamdani(); FL_LOG("=======================\n"); FL_LOG("Starting in 2 second"); FL_LOG("Example: Complex Mamdani"); FL_LOG("========================"); #ifdef _MSC_VER //Sleep(2); #else sleep(2); #endif ComplexMamdani(); FL_LOG("=======================\n"); FL_LOG("Starting in 2 second"); FL_LOG("Example: Simple Pendulum"); FL_LOG("========================"); #ifdef _MSC_VER //Sleep(2); #else sleep(2); #endif SimplePendulum(); FL_LOG("=======================\n"); FL_LOG("Starting in 2 second"); FL_LOG("Example: Simple Takagi-Sugeno"); FL_LOG("========================"); #ifdef _MSC_VER //Sleep(2); #else sleep(2); #endif SimpleTakagiSugeno(); FL_LOG("=======================\n"); FL_LOG("For further examples build the GUI..."); }
void Test::SimplePendulum() { FuzzyOperator& op = FuzzyOperator::DefaultFuzzyOperator(); FuzzyEngine engine("pendulum-3d",op); InputLVar* anglex = new InputLVar("AngleX"); std::vector<std::string> labels; labels.push_back("NEAR_0"); labels.push_back("NEAR_45"); labels.push_back("NEAR_90"); labels.push_back("NEAR_135"); labels.push_back("NEAR_180"); anglex->createTerms(5, LinguisticTerm::MF_SHOULDER, 0, 180, labels); engine.addInputLVar(anglex); InputLVar* anglez = new InputLVar("AngleZ"); labels.clear(); labels.push_back("NEAR_0"); labels.push_back("NEAR_45"); labels.push_back("NEAR_90"); labels.push_back("NEAR_135"); labels.push_back("NEAR_180"); anglez->createTerms(5, LinguisticTerm::MF_SHOULDER, 0, 180, labels); engine.addInputLVar(anglez); OutputLVar* forcex = new OutputLVar("ForceX"); labels.clear(); labels.push_back("NL"); labels.push_back("NS"); labels.push_back("ZR"); labels.push_back("PS"); labels.push_back("PL"); forcex->createTerms(5, LinguisticTerm::MF_TRIANGULAR, -1, 1, labels); engine.addOutputLVar(forcex); OutputLVar* forcez = new OutputLVar("ForceZ"); labels.clear(); labels.push_back("NL"); labels.push_back("NS"); labels.push_back("ZR"); labels.push_back("PS"); labels.push_back("PL"); forcez->createTerms(5, LinguisticTerm::MF_TRIANGULAR, -1, 1, labels); engine.addOutputLVar(forcez); RuleBlock* ruleblock = new RuleBlock("Rules"); ruleblock->addRule(new MamdaniRule("if AngleX is NEAR_180 then ForceX is NL", engine)); ruleblock->addRule(new MamdaniRule("if AngleX is NEAR_135 then ForceX is NS", engine)); ruleblock->addRule(new MamdaniRule("if AngleX is NEAR_90 then ForceX is ZR", engine)); ruleblock->addRule(new MamdaniRule("if AngleX is NEAR_45 then ForceX is PS", engine)); ruleblock->addRule(new MamdaniRule("if AngleX is NEAR_0 then ForceX is PL", engine)); ruleblock->addRule(new MamdaniRule("if AngleZ is NEAR_180 then ForceZ is NL", engine)); ruleblock->addRule(new MamdaniRule("if AngleZ is NEAR_135 then ForceZ is NS", engine)); ruleblock->addRule(new MamdaniRule("if AngleZ is NEAR_90 then ForceZ is ZR", engine)); ruleblock->addRule(new MamdaniRule("if AngleZ is NEAR_45 then ForceZ is PS", engine)); ruleblock->addRule(new MamdaniRule("if AngleZ is NEAR_0 then ForceZ is PL", engine)); engine.addRuleBlock(ruleblock); FL_LOG(engine.toString()); for (int i = 0; i < 180; i += 20) { engine.setInput("AngleX", i); engine.process(); FL_LOG("angle=" << i << "\tforce=" << engine.output("ForceX")); } }
void Engine::init() { FL_LOG(_log, "Engine initialize start"); m_settings.validate(); FL_LOG(_log, "Engine settings validated"); // If failed to init SDL throw exception. if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER) < 0) { throw SDLException(SDL_GetError()); } SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); TTF_Init(); FL_LOG(_log, "Creating event manager"); m_eventmanager = new EventManager(); FL_LOG(_log, "Creating pools"); m_imagepool = new ImagePool(); m_animpool = new AnimationPool(); m_soundclippool = new SoundClipPool(); m_imagepool->addResourceLoader(new SubImageLoader()); m_imagepool->addResourceLoader(new ImageLoader(m_vfs)); m_soundclippool->addResourceLoader(new OggLoader(m_vfs)); FL_LOG(_log, "Creating render backend"); std::string rbackend(m_settings.getRenderBackend()); if (rbackend == "SDL") { m_renderbackend = new RenderBackendSDL(); FL_LOG(_log, "SDL Render backend created"); } else { #ifdef HAVE_OPENGL m_renderbackend = new RenderBackendOpenGL(); FL_LOG(_log, "OpenGL Render backend created"); #else m_renderbackend = new RenderBackendSDL(); // Remember the choice so we pick the right graphics class. rbackend = "SDL"; FL_WARN(_log, "Tried to select OpenGL, even though it is not compiled into the engine. Falling back to SDL Render backend"); #endif } FL_LOG(_log, "Initializing render backend"); m_renderbackend->setChunkingSize(m_settings.getImageChunkingSize()); m_renderbackend->init(); FL_LOG(_log, "Creating main screen"); m_renderbackend->createMainScreen( m_settings.getScreenWidth(), m_settings.getScreenHeight(), static_cast<unsigned char>(m_settings.getBitsPerPixel()), m_settings.isFullScreen(), m_settings.getWindowTitle(), m_settings.getWindowIcon()); FL_LOG(_log, "Main screen created"); #ifdef HAVE_OPENGL if( rbackend != "SDL" ) { m_gui_graphics = new OpenGLGuiGraphics(*m_imagepool); } #endif if( rbackend == "SDL" ) { m_gui_graphics = new SdlGuiGraphics(*m_imagepool); } FL_LOG(_log, "Constructing GUI manager"); m_guimanager = new GUIManager(*m_imagepool); FL_LOG(_log, "Events bind to GUI manager"); m_eventmanager->addSdlEventListener(m_guimanager); FL_LOG(_log, "Creating default font"); m_defaultfont = m_guimanager->setDefaultFont( m_settings.getDefaultFontPath(), m_settings.getDefaultFontSize(), m_settings.getDefaultFontGlyphs()); FL_LOG(_log, "Initializing GUI manager"); m_guimanager->init(m_gui_graphics, m_settings.getScreenWidth(), m_settings.getScreenHeight()); FL_LOG(_log, "GUI manager initialized"); SDL_EnableUNICODE(1); FL_LOG(_log, "Creating sound manager"); m_soundmanager = new SoundManager(m_soundclippool); m_soundmanager->setVolume(static_cast<float>(m_settings.getInitialVolume()) / 10); FL_LOG(_log, "Creating model"); m_model = new Model(); FL_LOG(_log, "Adding pathers to model"); // m_model->adoptPather(new LinearPather()); m_model->adoptPather(new RoutePather()); FL_LOG(_log, "Adding grid prototypes to model"); m_model->adoptCellGrid(new SquareGrid()); m_model->adoptCellGrid(new HexGrid()); FL_LOG(_log, "Creating view"); m_view = new View(m_renderbackend, m_imagepool, m_animpool); FL_LOG(_log, "Creating renderers to view"); m_view->addRenderer(new CameraZoneRenderer(m_renderbackend, 0, m_imagepool)); m_view->addRenderer(new InstanceRenderer(m_renderbackend, 10, m_imagepool, m_animpool)); m_view->addRenderer(new GridRenderer(m_renderbackend, 20)); m_view->addRenderer(new CellSelectionRenderer(m_renderbackend, 30)); m_view->addRenderer(new BlockingInfoRenderer(m_renderbackend, 40)); m_view->addRenderer(new FloatingTextRenderer(m_renderbackend, 50, dynamic_cast<AbstractFont*>(m_defaultfont))); m_view->addRenderer(new QuadTreeRenderer(m_renderbackend, 60)); m_view->addRenderer(new CoordinateRenderer(m_renderbackend, 70, dynamic_cast<AbstractFont*>(m_defaultfont))); m_view->addRenderer(new GenericRenderer(m_renderbackend, 80, m_imagepool, m_animpool)); m_cursor = new Cursor(m_imagepool, m_animpool, m_renderbackend); FL_LOG(_log, "Engine intialized"); }
void Engine::init() { m_destroyed = false; FL_LOG(_log, "================== Engine initialize start ================="); m_timemanager = new TimeManager(); FL_LOG(_log, "Time manager created"); FL_LOG(_log, "Creating VFS"); m_vfs = new VFS(); FL_LOG(_log, "Adding root directory to VFS"); m_vfs->addSource( new VFSDirectory(m_vfs) ); m_vfs->addProvider( new DirectoryProvider() ); #ifdef HAVE_ZIP FL_LOG(_log, "Adding zip provider to VFS"); m_vfs->addProvider( new ZipProvider() ); #endif //m_vfs->addProvider(ProviderDAT2()); //m_vfs->addProvider(ProviderDAT1()); FL_LOG(_log, "Engine pre-init done"); // If failed to init SDL throw exception. if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER) < 0) { throw SDLException(SDL_GetError()); } SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); TTF_Init(); FL_LOG(_log, "Creating event manager"); m_eventmanager = new EventManager(); m_eventmanager->setMouseSensitivity(m_settings.getMouseSensitivity()); m_eventmanager->setMouseAcceleration(m_settings.getMouseAcceleration()); FL_LOG(_log, "Creating resource managers"); m_imagemanager = new ImageManager(); m_soundclipmanager = new SoundClipManager(); FL_LOG(_log, "Creating render backend"); std::string rbackend(m_settings.getRenderBackend()); if (rbackend == "SDL") { m_renderbackend = new RenderBackendSDL(m_settings.getColorKey()); FL_LOG(_log, "SDL Render backend created"); } else { #ifdef HAVE_OPENGL if (rbackend == "OpenGLe") { m_renderbackend = new RenderBackendOpenGLe(m_settings.getColorKey()); FL_LOG(_log, "OpenGLe Render backend created"); FL_LOG(_log, "This is highly experimental so bear in mind some features may not work/work correctly."); } else { m_renderbackend = new RenderBackendOpenGL(m_settings.getColorKey()); FL_LOG(_log, "OpenGL Render backend created"); } #else m_renderbackend = new RenderBackendSDL(m_settings.getColorKey()); // Remember the choice so we pick the right graphics class. rbackend = "SDL"; FL_WARN(_log, "Tried to select OpenGL, even though it is not compiled into the engine. Falling back to SDL Render backend"); #endif } FL_LOG(_log, "Initializing render backend"); m_renderbackend->setColorKeyEnabled(m_settings.isColorKeyEnabled()); // we always set this to false //m_renderbackend->setAlphaOptimizerEnabled(false); m_renderbackend->setImageCompressingEnabled(m_settings.isGLCompressImages()); m_renderbackend->setFramebufferEnabled(m_settings.isGLUseFramebuffer()); m_renderbackend->setNPOTEnabled(m_settings.isGLUseNPOT()); if (m_settings.isFrameLimitEnabled()) { m_renderbackend->setFrameLimitEnabled(true); m_renderbackend->setFrameLimit(m_settings.getFrameLimit()); } std::string driver = m_settings.getVideoDriver(); std::vector<std::string> drivers = m_devcaps.getAvailableDrivers(); if (driver != ""){ if (std::find (drivers.begin(), drivers.end(), driver) == drivers.end()) { FL_WARN(_log, "Selected driver is not supported for your Operating System! Reverting to default driver."); driver = ""; } } m_renderbackend->init(driver); FL_LOG(_log, "Querying device capabilities"); m_devcaps.fillDeviceCaps(); uint16_t bpp = m_settings.getBitsPerPixel(); m_screenMode = m_devcaps.getNearestScreenMode( m_settings.getScreenWidth(), m_settings.getScreenHeight(), bpp, rbackend, m_settings.isFullScreen()); FL_LOG(_log, "Creating main screen"); m_renderbackend->createMainScreen( m_screenMode, m_settings.getWindowTitle(), m_settings.getWindowIcon()); FL_LOG(_log, "Main screen created"); #ifdef HAVE_OPENGL if (m_settings.getLightingModel() != 0) { m_renderbackend->setLightingModel(m_settings.getLightingModel()); } #endif SDL_EnableUNICODE(1); FL_LOG(_log, "Creating sound manager"); m_soundmanager = new SoundManager(); m_soundmanager->setVolume(static_cast<float>(m_settings.getInitialVolume()) / 10); FL_LOG(_log, "Creating renderers"); m_offrenderer = new OffRenderer(m_renderbackend); m_targetrenderer = new TargetRenderer(m_renderbackend); m_renderers.push_back(new InstanceRenderer(m_renderbackend, 10)); m_renderers.push_back(new GridRenderer(m_renderbackend, 20)); m_renderers.push_back(new CellSelectionRenderer(m_renderbackend, 30)); m_renderers.push_back(new BlockingInfoRenderer(m_renderbackend, 40)); m_renderers.push_back(new FloatingTextRenderer(m_renderbackend, 50)); m_renderers.push_back(new QuadTreeRenderer(m_renderbackend, 60)); m_renderers.push_back(new CoordinateRenderer(m_renderbackend, 70)); m_renderers.push_back(new GenericRenderer(m_renderbackend, 80)); m_renderers.push_back(new LightRenderer(m_renderbackend, 90)); FL_LOG(_log, "Creating model"); m_model = new Model(m_renderbackend, m_renderers); FL_LOG(_log, "Adding pathers to model"); m_model->adoptPather(new RoutePather()); FL_LOG(_log, "Adding grid prototypes to model"); m_model->adoptCellGrid(new SquareGrid()); m_model->adoptCellGrid(new HexGrid()); m_cursor = new Cursor(m_renderbackend); FL_LOG(_log, "Engine intialized"); }
void Function::main() { Function f; std::string text = "3+4*2/(1-5)^2^3"; FL_LOG(f.toPostfix(text)); FL_LOG("P: " << f.parse(text)->toInfix()); FL_LOG(">" << f.parse(text)->evaluate()); //3 4 2 * 1 5 - 2 3 ^ ^ / + f.variables["y"] = 1.0; text = "sin(y*x)^2/x"; FL_LOG("pre: " << f.parse(text)->toPrefix()); FL_LOG("in: " << f.parse(text)->toInfix()); FL_LOG("pos: " << f.parse(text)->toPostfix()); f.load(text); FL_LOG("Result: " << f.membership(1)); //y x * sin 2 ^ x / text = "(Temperature is High and Oxigen is Low) or " "(Temperature is Low and (Oxigen is Low or Oxigen is High))"; FL_LOG(f.toPostfix(text)); f.variables["pi"] = 3.14; text = "-5 *4/sin(-pi/2)"; FL_LOG(f.toPostfix(text)); try { FL_LOG(f.parse(text)->evaluate()); } catch (std::exception& e) { FL_LOG(e.what()); } f.variables["pi"] = 3.14; text = "~5 *4/sin(~pi/2)"; FL_LOG(f.toPostfix(text)); try { FL_LOG(f.parse(text)->evaluate(&f.variables)); } catch (std::exception& e) { FL_LOG(e.what()); } }
void TimeManager::printStatistics() const { FL_LOG(_log, LMsg("Timers: ") << m_events_list.size()); }