bool convertSpriteBank8to32 (struct spriteBank *sprites) { if (! sprites->total) return true; sprite * newsprites = new sprite [sprites->total]; if (! newsprites) { return errorBox ("Can't convert sprite bank", "Out of memory."); } for (int i = 0; i< sprites->total; i++) { unsigned char * data = new unsigned char [sprites->sprites[i].height*sprites->sprites[i].width*4]; if (! data) { while (--i >= 0) { delete newsprites[i].data; } delete newsprites; return errorBox ("Can't convert sprite bank", "Out of memory."); } unsigned char s; int fromhere = 0; for (int y = 0; y < sprites->sprites[i].height; y ++) { for (int x = 0; x < sprites->sprites[i].width; x ++) { unsigned char * target = data + 4*sprites->sprites[i].width*y + x*4; s = sprites->sprites[i].data[fromhere++]; if (s) { target[0] = sprites->myPalette.r[s]; target[1] = sprites->myPalette.g[s]; target[2] = sprites->myPalette.b[s]; target[3] = 255; } else { target[0] = 0; target[1] = 0; target[2] = 0; target[3] = 0; } } } newsprites[i].data = data; newsprites [i].width = sprites->sprites[i].width; newsprites [i].height = sprites->sprites[i].height; newsprites [i].xhot = sprites->sprites[i].xhot; newsprites [i].yhot = sprites->sprites[i].yhot; newsprites [i].tex_x = sprites->sprites[i].tex_x; newsprites [i].texNum = sprites->sprites[i].texNum; } for (int i = 0; i< sprites->total; i++) { delete sprites->sprites[i].data; } delete sprites->sprites; sprites->sprites = newsprites; sprites->type = 2; return true; }
void SludgeProjectManager::on_comp_gamebutton_clicked() { char cmd[1000]; char *file = getFullPath(gameFile); #ifdef __WIN32 int cmdSuccess; int lastSlash = 0; char engineDir[1000]; sprintf(engineDir, "%s", workingDir); for (int k = 0; engineDir[k] != 0; k++) { if (engineDir[k] == '\\') { lastSlash = k; } } sprintf(engineDir + lastSlash + 1, "Engine"); sprintf(cmd, "\"%s\\SLUDGE Engine.exe\"", engineDir); cmdSuccess = sh_cmd(engineDir, cmd, file); if (!cmdSuccess) { errorBox("Couldn't find SLUDGE Engine", "The SLUDGE Engine was expected at ..\\Engine\\SLUDGE Engine.exe relative to the Project Manager executable. Make sure it's there to make the Run Game button work."); } #else sprintf(cmd, "%s", "sludge-engine"); sh_cmd(workingDir, cmd, file); #endif deleteString(file); }
/** * @brief Connects the client to the server. * @param QString host - the host name * @param int port - the port used by the server * @param QString pseudo - the client's name */ void MainWindow::serverConnection(QString host, int port, QString pseudo) { strcpy(_player.name, pseudo.toStdString().c_str()); init_host(_ptr_host, (char*)host.toStdString().c_str(), &_local_addr); assign_port(&_local_addr, port); _player.socket = create_socket(); // Have to test if the client can be connect to the server if(server_connection(_player.socket, _local_addr) >= 0) { qDebug() << "[Server_connection] : Client is connected"; startListeners(); // Have to start listeners threads // Ask to the server to add the new client into its array of players qDebug() << "[Server_connection] : Sending information to the server" << _player.name; frame f = make_frame(_local_addr.sin_addr, _local_addr.sin_addr, CONNECT, _player.name); write_to_server(_player.socket, &f); // When the client is connected, display the mainPage of the application ui->stackedWidget->slideInIdx(1, SlidingStackedWidget::BOTTOM2TOP); } else { //Connection is impossible QMessageBox errorBox(QMessageBox::Question,tr("error"),tr("Can't establish the connection with the server."),QMessageBox::Cancel); errorBox.exec(); } }
void SludgeFloorMaker::on_filechooserbutton_file_set(GtkFileChooser *theChooser) { char *filename; gboolean success = 0; filename = gtk_file_chooser_get_filename(theChooser); if (filename == NULL) return; flipBackslashes(&filename); if (strlen(filename) > 4) { char * extension = filename + strlen(filename) - 4; if (!strcmp(extension, ".png") || !strcmp(extension, ".PNG")) { success = loadSpriteFromPNG(filename, &backdrop, 0); } else if (!strcmp(extension, ".tga") || !strcmp(extension, ".TGA")) { success = loadSpriteFromTGA(filename, &backdrop, 0); } } else { errorBox("Can't load image", "I don't recognise the file type. TGA and PNG are the supported file types."); } if (success) { setFolderFromFilename(filename); backdrop.sprites[0].height = -backdrop.sprites[0].height; activateZoomButtons(backdrop.sprites[0].width, -backdrop.sprites[0].height); showStatusbar(backdrop.sprites[0].width, -backdrop.sprites[0].height); on_zoom_fit_clicked(); reshape(); render_timer_event(theDrawingarea); } g_free(filename); }
bool Scripting::pluginActionError(const QString &actionStr, const QString &pluginName, const QString &errorStr, bool isQuiet) { if (!isQuiet) { QMessageBox errorBox(QMessageBox::Warning, "Plugin action error", QString("Failed '%1' for plugin '%2':\n%3").arg(actionStr).arg(pluginName).arg(errorStr), QMessageBox::Ok, NULL); errorBox.exec(); } return false; }
/* bool savePNGSprite (FILE * fp, struct spriteBank *sprites, int index, bool sig) { png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { fclose (fp); return false; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr){ png_destroy_write_struct(&png_ptr, (png_infopp)NULL); fclose (fp); return false; } png_init_io(png_ptr, fp); if (!sig) png_set_sig_bytes(png_ptr, 8); const int h = 21, w = 21; png_set_IHDR(png_ptr, info_ptr, w, h, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); unsigned char * row_pointers[h]; unsigned char data[w*h*4]; for (int i = 0; i < h; i++) { row_pointers[i] = data + 4 * i * w; if (!(i % 20) || (i > (h-2))) { for (int x = 0; x < w; x++) { *(unsigned char *)(row_pointers[i]+x*4) = 255; *(unsigned char *)(row_pointers[i]+x*4+1) = 0; *(unsigned char *)(row_pointers[i]+x*4+2) = *(unsigned char *)(row_pointers[i]+x*4+3) = 255; } } else { for (int x = 0; x < w; x++) { if (x % 20 && x < (w-1)) { *(unsigned char *)(row_pointers[i]+x*4) = *(unsigned char *)(row_pointers[i]+x*4+1) = *(unsigned char *)(row_pointers[i]+x*4+2) = 0; *(unsigned char *)(row_pointers[i]+x*4+3) = 0; } else { *(unsigned char *)(row_pointers[i]+x*4) = 255; *(unsigned char *)(row_pointers[i]+x*4+1) = 0; *(unsigned char *)(row_pointers[i]+x*4+2) = 255; *(unsigned char *)(row_pointers[i]+x*4+3) = 255; } } } } png_set_rows(png_ptr, info_ptr, row_pointers); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); return true; } */ bool savePNGSprite (FILE * fp, struct spriteBank *sprites, int index, bool sig) { if (sprites->sprites[index].width < 1) return errorBox ("Error saving", "Can't save a sprite that has no width."); if (sprites->sprites[index].height < 1) { sprites->sprites[index].height = 1; unsigned char * d = new unsigned char [sprites->sprites[index].width*4]; if (!d) return errorBox ("Error saving", "Out of RAM memory."); for (int i = 0; i < sprites->sprites[index].width*4; i++) { d[i] = 0; } delete sprites->sprites[index].data; sprites->sprites[index].data = d; } png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { fclose (fp); return false; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr){ png_destroy_write_struct(&png_ptr, (png_infopp)NULL); fclose (fp); return false; } png_init_io(png_ptr, fp); if (!sig) png_set_sig_bytes(png_ptr, 8); png_set_IHDR(png_ptr, info_ptr, sprites->sprites[index].width, sprites->sprites[index].height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); unsigned char * row_pointers[sprites->sprites[index].height]; for (int i = 0; i < sprites->sprites[index].height; i++) { row_pointers[i] = sprites->sprites[index].data + 4*i*sprites->sprites[index].width; } png_set_rows(png_ptr, info_ptr, row_pointers); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); return true; }
static void warningOpenSourceFile (char * fileName) { char * wholePath = new char[strlen (sourceDirectory) + strlen (fileName) + 2]; if (wholePath) { sprintf (wholePath, "%s\\%s", sourceDirectory, fileName); if ((unsigned long) ShellExecute (warningWindowH, "open", wholePath, NULL, NULL, SW_SHOWNORMAL) <= 31) { errorBox ("Couldn't launch ", wholePath); } delete wholePath; } }
//------------------------------------------------------------------------- void MainWindow::displayError(const char* errorText, const char* detailedText) { QMessageBox errorBox(this); errorBox.setText(errorText); if (detailedText != 0) { errorBox.setDetailedText(detailedText); } errorBox.setIcon(QMessageBox::Warning); errorBox.setSizeGripEnabled(true); errorBox.exec(); }
void SludgeApplication::open(char* filename) { if (!loadFile (filename)) { errorBox ("Error", "Loading file failed."); } else { setFilename(filename); setFolderFromFilename(filename); postOpen (); } }
void SludgeZBufferMaker::postNew() { GtkWidget *dialog; dialog = gtk_file_chooser_dialog_new("Load file to zBuffer", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); setFileChooserFilters(GTK_FILE_CHOOSER (dialog), FALSE, TRUE); if (currentFolder[0] != 0) { gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER (dialog), currentFolder); } if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { char *filename; filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (dialog)); flipBackslashes(&filename); if (!loadZBufferFromTGA(filename, &backdrop)) { errorBox("Error", "Loading TGA file failed."); } else { setFolderFromFilename(filename); setFilename(filename); int i, lastSlash; for (i = 0; filename[i] != 0; i++) { if (filename[i] == '/') lastSlash = i; } currentShortname[i-lastSlash-4] = 'z'; currentShortname[i-lastSlash-3] = 'b'; currentShortname[i-lastSlash-2] = 'u'; currentFilename[0] = 0; gtk_window_set_title(GTK_WINDOW(theWindow), getWindowTitle()); setFileChanged(); postOpen(); } g_free(filename); } gtk_widget_destroy(dialog); setupButtons(); }
bool exportToPNG (const char * file, struct spriteBank *sprites, int index) { if (sprites->type < 2) return errorBox ("Export failed", "Sorry - can only export 32-bit pictures at the moment."); FILE *fp = fopen(file, "wb"); if (!fp) { return false; } int ret = savePNGSprite (fp, sprites, index, true); fclose(fp); return ret; }
void runCompiledGame () { char * wholePath = new char[strlen (sourceDirectory) + strlen (settings.finalFile) + 20]; if (wholePath) { sprintf (wholePath, "%s\\%s%s", sourceDirectory, settings.finalFile, settings.forceSilent ? " (silent).slg" : ".slg"); unsigned long reply = (unsigned long) ShellExecute (mainWin, "open", wholePath, NULL, NULL, SW_SHOWNORMAL); if (reply <= 31) { errorBox ("Compiled OK, but can't determine the location of the SLUDGE engine on this machine...", "You HAVE installed the SLUDGE engine, haven't you?"); } delete wholePath; } }
void Scripting::createDefaultPluginDir() { auto pluginDir = getPluginDir(); if (!pluginDir.isEmpty() && QDir(pluginDir).exists()) { return; } pluginDir = getDefaultPluginDir(); if (!QDir().mkpath(pluginDir)) { QMessageBox errorBox(QMessageBox::Warning, "Python Plugin Manager: Error", QString("Cannot create plugin directory:\n%1").arg(pluginDir), QMessageBox::Ok, NULL); errorBox.exec(); return; } setPluginDir(pluginDir); }
void SludgeApplication::on_save() { if (currentFilename[0] != 0) { if (!saveFile (currentFilename)) { errorBox ("Error", "Saving file failed."); } else { gtk_window_set_title (GTK_WINDOW(theWindow), currentShortname); fileChanged = FALSE; } } else { saveToFile(); } }
void SludgeApplication::saveToFile() { GtkWidget *dialog; GtkFileFilter *filter; dialog = gtk_file_chooser_dialog_new ("Save File", NULL, GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, NULL); gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE); filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, getFilterName()); gtk_file_filter_add_pattern(filter, getFilterPattern()); gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dialog), filter); if (currentShortname[0] != 0) { gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), currentShortname); } if (currentFolder[0] != 0) { gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), currentFolder); } if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { char *filename; filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)); flipBackslashes(&filename); if (!saveFile (filename)) { errorBox ("Error", "Saving file failed."); } else { setFilename(filename); setFolderFromFilename(filename); } g_free (filename); } gtk_widget_destroy (dialog); }
void SludgeFloorMaker::button1Release(int local_pointx, int local_pointy) { int xx, yy; awaitButton1Release = FALSE; selx2 = xx = (local_pointx+x)*zmul; sely2 = yy = (local_pointy-y)*zmul; lit = snapToClosest(&xx, &yy, getFloor()); litX = xx; litY = yy; if (lit && (xx != selx1 || yy != sely1)) { selx2 = xx; sely2 = yy; } selection = 0; switch (mode) { case 1: // Move vertices if (moveVertices(selx1, sely1, selx2, sely2, getFloor())) { setFileChanged(); } else { errorBox("Can't move vertex", "Sorry - that vertex is already contained in one or more of the polygons you're changing."); return; } break; case 4: // Split lines splitLine(selx1, sely1, selx2, sely2, getFloor()); setFileChanged(); break; case 5: // Split segments struct polyList * firstPoly = getFloor(); splitPoly(selx1, sely1, selx2, sely2, &firstPoly); setFloor(firstPoly); setFileChanged(); break; } }
/* * --------------------------------------------------- * Slots * --------------------------------------------------- */ void Grid::extract() { // sness if ( _collection->getNumTracks() > 0 ) { int index = 0; // !!! use itunes to generate the collection file rather then using a file ofstream featureFile; featureFile.open("margrid_train.mf", std::ios::out | std::ios::binary); //featureFile.open("music.mf"); _collection->generatePlayList(featureFile, playlist_.c_str()); extractAction("margrid_train.mf"); } else if (trainFile_.length() > 0) { cout << "Grid::extract() :: trainFile_.length() > 0" << endl; cout << "trainFile_=" << trainFile_ << endl; extractAction(trainFile_); } else { emit errorBox("Need to load a collection of audio files first!"); } }
void SludgeProjectManager::on_compile() { //Switch to the "Compiler Errors" notebook to make sure the TableView is realized: gtk_notebook_set_current_page(notebook, 1); gtk_widget_set_sensitive(closeCompilerButton, FALSE); gtk_widget_set_sensitive(runGameButton, FALSE); gtk_widget_show(GTK_WIDGET(compilerDialog)); compilerInfoQueue = g_async_queue_new(); GError *error = NULL; gdk_threads_leave (); g_thread_create(compile_hook, NULL, FALSE, &error); gdk_threads_enter (); if (error != NULL) { errorBox("Could not create a new thread for compiling!", error->message); g_error_free(error); return; } }
GridDisplay::GridDisplay(int winSize, Tracklist *tracklist, Grid* grid_, QWidget *parent) : MyDisplay(tracklist, parent), _winSize(winSize) { this->grid_ = grid_; _cellSize = grid_->getCellSize(_winSize); setMinimumSize(winSize, winSize); setMouseTracking(true); setAcceptDrops(true); squareHasInitialized.resize(grid_->getHeight() * grid_->getWidth()); for(int i = 0; i < grid_->getHeight() * grid_->getWidth(); i++) squareHasInitialized[i] = false; oldXPos = -1; oldYPos = -1; oldX1Pos = -1; oldY1Pos = -1; fullScreenMouseOn = false; initDone = false; fullScreenTimer = new QTimer(this); fullScreenTimer->setInterval(150); colourMapMode_ = false; connect(this, SIGNAL(clearMode()), grid_, SLOT(clearMode())); connect(this, SIGNAL(extractMode()), grid_, SLOT(setExtractMode())); connect(this, SIGNAL(trainMode()), grid_, SLOT(setTrainMode())); connect(this, SIGNAL(predictMode()), grid_, SLOT(setPredictMode())); connect(this, SIGNAL(initMode()), grid_, SLOT(setInitMode())); connect(this, SIGNAL(savePredictionGridSignal(QString)), grid_, SLOT(savePredictionGrid(QString))); connect(this, SIGNAL(openPredictionGridSignal(QString)), grid_, SLOT(openPredictionGrid(QString))); connect(grid_, SIGNAL(repaintSignal()), this, SLOT(repaintSlot())); connect(this, SIGNAL(cancelButtonPressed()), grid_, SLOT(cancelPressed())); connect(this, SIGNAL(hashLoadPressed()), grid_, SLOT(openHash())); connect(fullScreenTimer, SIGNAL(timeout()), this, SLOT(fullScreenMouseMove())); connect(grid_, SIGNAL(errorBox(QString)), this, SLOT(showErrorMessage(QString))); connect(this, SIGNAL(resetGridAction()), grid_, SLOT(resetGridSlot())); }
bool loadZBufferFromTGA (const char * fileName, spriteBank *loadhere) { unsigned char * pointer; unsigned short int t1, t2; palCol thePalette[256]; int numPanels = 1; int panels[16]; int cutoff[16]; int color, panel; unsigned char n; unsigned char * data; // Open the file FILE * fp = fopen (fileName, "rb"); if (fp == NULL) { errorBox ("Error", "Can't open that image file!"); return false; } // Grab the header TGAHeader imageHeader; const char * errorBack; errorBack = readTGAHeader (imageHeader, fp, thePalette); if (errorBack) { errorBox ("Error reading TGA file", errorBack); return false; } unsigned short (* readColFunction) (FILE * fp, int bpc, palCol thePalette[], int x, int y) = imageHeader.compressed ? readCompressedColour : readAColour; data = new unsigned char [imageHeader.width * imageHeader.height]; panels[0] = cutoff[0] = 0; for (t2 = imageHeader.height; t2; t2 --) { pointer = data + (t2-1)*imageHeader.width; for (t1 = 0; t1 < imageHeader.width; t1 ++) { color = readColFunction (fp, imageHeader.pixelDepth, thePalette, 0, 0); if (color) { for (n = 1; n < numPanels; n ++) { if (panels[n] == color) break; } if (n == numPanels) { if (n < 16) { panels[n] = color; numPanels ++; if (n) cutoff[n] = t2; } else { delete data; errorBox ("Error reading TGA file", "Too many colours. Max 16 are allowed for making z-buffers. Each separate colour will become a z-buffer. If you need more, use sprites instead."); return false; } } panel = n; } else { panel = 0; } * (pointer ++) = panel; } } fclose (fp); if (numPanels<2) { delete data; errorBox ("Error reading TGA file", "Can't find any z-buffers in the file."); return false; } loadhere->total = numPanels; loadhere->sprites = new sprite [loadhere->total]; for (n = 0; n < loadhere->total; n ++) { loadhere->sprites[n].width = imageHeader.width; loadhere->sprites[n].height = -imageHeader.height; loadhere->sprites[n].xhot = 0; loadhere->sprites[n].yhot = 0; loadhere->sprites[n].special = cutoff[n]; loadhere->sprites[n].tex_x = 0; loadhere->sprites[n].texNum = n; loadhere->myPalette.tex_names[n] = 0; loadhere->myPalette.tex_h[n] = imageHeader.height; loadhere->myPalette.tex_w[n] = imageHeader.width; if (n) loadhere->sprites[n].data = new unsigned char [imageHeader.width * imageHeader.height]; else loadhere->sprites[n].data = data; } for (int y = 0; y < imageHeader.height; y ++) { for (int x = 0; x < imageHeader.width; x ++) { n = loadhere->sprites[0].data[y*imageHeader.width+x]; for (int i = 1; i < loadhere->total; i ++) { loadhere->sprites[i].data[y*imageHeader.width+x] = (n == i) ? 255: 0; } } } return true; }
void ZLDialogManager::errorBox(const ZLResourceKey &key) const { errorBox(key, dialogMessage(key)); }
void SludgeProjectManager::on_treeview_row_activated(GtkTreeView *theTreeView, GtkTreePath *thePath, GtkTreeViewColumn *theColumn, whichTreeview whichOne) { GtkTreeModel *treeModel; const char *cmd; char *tx, *tx1; if (currentFilename[0] == 0) return; getSourceDirFromName(currentFilename); gotoSourceDirectory(); treeModel = gtk_tree_view_get_model(theTreeView); int filenameColumn = 0; switch (whichOne) { case ERROR_TREEVIEW: filenameColumn = ERRORS_COLUMN_FILENAME; case FILE_TREEVIEW: cmd = editor; break; default: break; } GtkTreeIter iter; gtk_tree_model_get_iter(treeModel, &iter, thePath); if (whichOne == ERROR_TREEVIEW) { gboolean hasFilename; gtk_tree_model_get(treeModel, &iter, ERRORS_COLUMN_HAS_FILENAME, &hasFilename, -1); if (!hasFilename) { gtk_tree_model_get(treeModel, &iter, ERRORS_COLUMN_OVERVIEW, &tx, -1); errorBox("Error overview", tx); g_free(tx); return; } } gtk_tree_model_get(treeModel, &iter, filenameColumn, &tx1, -1); tx = g_filename_from_utf8(tx1, -1, NULL, NULL, NULL); g_free(tx1); char * extension; gint *indices; struct errorLinkToFile * index; int i, row; switch (whichOne) { case FILE_TREEVIEW: extension = tx + strlen(tx) - 4; if ((strlen(tx) > 4) && (!strcmp(extension, ".tra") || !strcmp(extension, ".TRA"))) { #ifdef __WIN32 cmd = "sludge-translationeditor.exe"; #else cmd = "sludge-translationeditor"; #endif } break; case RESOURCE_TREEVIEW: extension = tx + strlen(tx) - 4; if (strlen(tx) > 4) { if (!strcmp(extension, ".flo") || !strcmp(extension, ".FLO")) { #ifdef __WIN32 cmd = "sludge-floormaker.exe"; #else cmd = "sludge-floormaker"; #endif } else if (!strcmp(extension, ".duc") || !strcmp(extension, ".DUC")) { #ifdef __WIN32 cmd = "sludge-spritebankeditor.exe"; #else cmd = "sludge-spritebankeditor"; #endif } else if (!strcmp(extension, ".zbu") || !strcmp(extension, ".ZBU")) { #ifdef __WIN32 cmd = "sludge-zbuffermaker.exe"; #else cmd = "sludge-zbuffermaker"; #endif } else if (!strcmp(extension, ".png") || !strcmp(extension, ".PNG") || !strcmp(extension, ".tga") || !strcmp(extension, ".TGA")) { cmd = imageViewer; } else if (!strcmp(extension, ".wav") || !strcmp(extension, ".WAV") || !strcmp(extension, ".ogg") || !strcmp(extension, ".OGG") || !strcmp(extension, "flac") || !strcmp(extension, "FLAC")) { cmd = audioPlayer; } else if (!strcmp(extension, ".mod") || !strcmp(extension, ".MOD") || !strcmp(extension, ".s3m") || !strcmp(extension, ".S3M")) { cmd = modPlayer; } else { extension = tx + strlen(tx) - 3; if (strlen(tx) > 3 && (!strcmp(extension, ".it") || !strcmp(extension, ".IT") || !strcmp(extension, ".xm") || !strcmp(extension, ".XM"))) { cmd = modPlayer; } } } break; default: break; } if (cmd[0] != 0 && tx) { sh_cmd(workingDir, cmd, getFullPath(tx)); } /* else { char buf[1000]; GError *error = NULL; sprintf(buf, "file://%s", getFullPath(tx)); gtk_show_uri (NULL, buf, GDK_CURRENT_TIME, &error); if (error != NULL) { errorBox("Opening file failed!", error->message); g_error_free(error); } } */ g_free(tx); }
bool loadSpriteFromPNG (const char * file, struct spriteBank *sprites, int index) { if (sprites->type<2) { char * error = joinStrings(file, "\n\nPNG files currently not supported in palette mode. Change to 32-bit mode and try again."); errorBox ("Can't open PNG file", error); delete error; return false; } // Open the file FILE * fp = fopen (file, "rb"); if (fp == NULL) { char * error = joinStrings(file, "\n\nThe file can't be opened. I don't know why."); errorBox ("Can't open PNG file", error); delete error; return false; } char tmp[10]; size_t bytes_read = fread(tmp, 1, 8, fp); if (bytes_read != 8 && ferror (fp)) { fprintf(stderr, "Reading error in loadSpriteFromPNG.\n"); } if (png_sig_cmp((png_byte *) tmp, 0, 8)) { fclose (fp); char * error = joinStrings(file, "\n\nIt doesn't appear to be a valid PNG image."); errorBox ("Can't open PNG file", error); delete error; return false; } png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { fclose (fp); char * error = joinStrings(file, "\n\nError reading the file."); errorBox ("Can't open PNG file", error); delete error; return false; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL); fclose (fp); char * error = joinStrings(file, "\n\nError reading the file."); errorBox ("Can't open PNG file", error); delete error; return false; } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); fclose (fp); char * error = joinStrings(file, "\n\nError readin the file"); return errorBox ("Can't open PNG file", error); } png_init_io(png_ptr, fp); // Tell libpng which file to read png_set_sig_bytes(png_ptr, 8); // 8 bytes already read png_read_info(png_ptr, info_ptr); png_uint_32 width, height; int bit_depth, color_type, interlace_type, compression_type, filter_method; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method); if (bit_depth < 8) png_set_packing(png_ptr); png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); if (bit_depth == 16) png_set_strip_16(png_ptr); png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); png_read_update_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method); int rowbytes = png_get_rowbytes(png_ptr, info_ptr); unsigned char * row_pointers[height]; unsigned char * data = new unsigned char [rowbytes*height]; for (int i = 0; i<height; i++) row_pointers[i] = data + i*rowbytes; png_read_image(png_ptr, (png_byte **) row_pointers); png_read_end(png_ptr, NULL); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose (fp); if (sprites->sprites[index].data) delete sprites->sprites[index].data; sprites->sprites[index].data = data; sprites->sprites[index].width = width; sprites->sprites[index].height = height; int n, r, g, b; for (int x=0; x<width;x++) { for (int y=0; y<height; y++) { if (! sprites->sprites[index].data[4*width*y + x*4 + 3]) { n = r = g = b = 0; if (x>0 && sprites->sprites[index].data[4*width*y + (x-1)*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*y + (x-1)*4]; g+= sprites->sprites[index].data[4*width*y + (x-1)*4+1]; b+= sprites->sprites[index].data[4*width*y + (x-1)*4+2]; } if (x<width-1 && sprites->sprites[index].data[4*width*y + (x+1)*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*y + (x+1)*4]; g+= sprites->sprites[index].data[4*width*y + (x+1)*4+1]; b+= sprites->sprites[index].data[4*width*y + (x+1)*4+2]; } if (y>0 && sprites->sprites[index].data[4*width*(y-1) + x*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*(y-1) + x*4]; g+= sprites->sprites[index].data[4*width*(y-1) + x*4+1]; b+= sprites->sprites[index].data[4*width*(y-1) + x*4+2]; } if (y<height-1 && sprites->sprites[index].data[4*width*(y+1) + x*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*(y+1) + x*4]; g+= sprites->sprites[index].data[4*width*(y+1) + x*4+1]; b+= sprites->sprites[index].data[4*width*(y+1) + x*4+2]; } if (n) { r /= n; g /= n; b /= n; sprites->sprites[index].data[4*width*y + x*4]=r; sprites->sprites[index].data[4*width*y + x*4+1]=g; sprites->sprites[index].data[4*width*y + x*4+2]=b; } } } } loadSpriteTexture (sprites, index); return true; }
bool loadSpriteFromTGA (const char * file, struct spriteBank *sprites, int index) { palCol thePalette[256]; // Open the file FILE * fp = fopen (file, "rb"); if (fp == NULL) { char * error = joinStrings(file, "\n\nThe file can't be opened. I don't know why."); errorBox ("Can't open TGA file", error); delete error; return false; } // Grab the header TGAHeader imageHeader; const char * errorBack; errorBack = readTGAHeader (imageHeader, fp, thePalette); if (errorBack) { fclose (fp); char * error = joinStrings(file, "\n\n", errorBack); errorBox ("Can't open TGA file", error); delete error; return false; } unsigned char *data; if (sprites->type < 2) { data = new unsigned char[imageHeader.height * imageHeader.width]; if (! data) { fclose (fp); errorBox ("Can't create sprite", "Out of memory."); return false; } unsigned char palSize = sprites->myPalette.total; unsigned char r,g,b; int c; for (int t2 = imageHeader.height-1; t2>=0; t2 --) { for (int t1 = 0; t1 < imageHeader.width; t1 ++) { if (! imageHeader.compressed) { grabRGB (fp, imageHeader.pixelDepth, r, g, b, thePalette); } else { grabRGBCompressed (fp, imageHeader.pixelDepth, r, g, b, thePalette); } if (sprites->type == 1) data[t2*imageHeader.width+t1] = findClosestPal (&sprites->myPalette, r, g, b); else { if ((c = findOrAddPal (&sprites->myPalette, r, g, b)) < 0) { fclose(fp); errorBox ("Can't create sprite", "The sprite bank palette doesn't have enough room left to add the colours. Change the palette mode to locked or 32-bit and try again."); sprites->myPalette.total = palSize; delete data; return false; } data[t2*imageHeader.width+t1] = c; } } } } else { data = new unsigned char[imageHeader.height * imageHeader.width * 4]; if (! data) { fclose (fp); errorBox ("Can't create sprite", "Out of memory."); return false; } unsigned char r,g,b,a; fprintf (stderr, "Compressed: %d (%d)\n", imageHeader.compressed, imageHeader.pixelDepth); for (int t2 = imageHeader.height-1; t2>=0; t2 --) { for (int t1 = 0; t1 < imageHeader.width; t1 ++) { if (! imageHeader.compressed) { grabRGBA (fp, imageHeader.pixelDepth, r, g, b, a, thePalette); } else { grabRGBACompressed (fp, imageHeader.pixelDepth, r, g, b, a, thePalette); } data[t2*imageHeader.width*4+t1*4] = r; data[t2*imageHeader.width*4+t1*4+1] = g; data[t2*imageHeader.width*4+t1*4+2] = b; data[t2*imageHeader.width*4+t1*4+3] = a; } } } fclose (fp); if (sprites->sprites[index].data) delete sprites->sprites[index].data; sprites->sprites[index].data = data; sprites->sprites[index].width = imageHeader.width; sprites->sprites[index].height = imageHeader.height; if (sprites->type>=2) { int n, r, g, b; int width = imageHeader.width; int height = imageHeader.height; for (int x=0; x<width;x++) { for (int y=0; y<height; y++) { if (! sprites->sprites[index].data[4*width*y + x*4 + 3]) { n = r = g = b = 0; if (x>0 && sprites->sprites[index].data[4*width*y + (x-1)*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*y + (x-1)*4]; g+= sprites->sprites[index].data[4*width*y + (x-1)*4+1]; b+= sprites->sprites[index].data[4*width*y + (x-1)*4+2]; } if (x<width-1 && sprites->sprites[index].data[4*width*y + (x+1)*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*y + (x+1)*4]; g+= sprites->sprites[index].data[4*width*y + (x+1)*4+1]; b+= sprites->sprites[index].data[4*width*y + (x+1)*4+2]; } if (y>0 && sprites->sprites[index].data[4*width*(y-1) + x*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*(y-1) + x*4]; g+= sprites->sprites[index].data[4*width*(y-1) + x*4+1]; b+= sprites->sprites[index].data[4*width*(y-1) + x*4+2]; } if (y<height-1 && sprites->sprites[index].data[4*width*(y+1) + x*4 + 3]) { n++; r+= sprites->sprites[index].data[4*width*(y+1) + x*4]; g+= sprites->sprites[index].data[4*width*(y+1) + x*4+1]; b+= sprites->sprites[index].data[4*width*(y+1) + x*4+2]; } if (n) { r /= n; g /= n; b /= n; sprites->sprites[index].data[4*width*y + x*4]=r; sprites->sprites[index].data[4*width*y + x*4+1]=g; sprites->sprites[index].data[4*width*y + x*4+2]=b; } } } } } loadSpriteTexture (sprites, index); return true; }
bool loadSpriteBank (const char * filename, spriteBank *loadhere) { int i, total, picwidth, picheight, spriteBankVersion = 0, howmany, startIndex; int totalwidth[65535], maxheight[65535]; int numTextures = 0; // Open the file FILE * fp = fopen (filename, "rb"); if (fp == NULL) { return errorBox ("Can't open sprite bank", "The file can't be opened. I don't know why."); } total = get2bytes(fp); if (! total) { spriteBankVersion = fgetc(fp); if (spriteBankVersion == 1) { total = 0; } else { total = get2bytes(fp); } } if (spriteBankVersion > 3) return errorBox ("Error opening sprite bank", "Unsupported sprite bank file format"); if (total <= 0) return errorBox ("Error opening sprite bank", "No sprites in bank or invalid sprite bank file"); if (spriteBankVersion == 3) { loadhere->type = 2; loadhere->total = total; loadhere->sprites = new sprite [total]; for (int index = 0; index < total; index ++) { loadhere->sprites[index].xhot = getSigned (fp); loadhere->sprites[index].yhot = getSigned (fp); png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { fclose (fp); return errorBox ("Can't open PNG file", "Error reading the file."); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL); fclose (fp); return errorBox ("Can't open PNG file", "Error reading the file."); } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); fclose (fp); return errorBox ("Can't open PNG file", "Error reading the file."); } png_init_io(png_ptr, fp); // Tell libpng which file to read png_set_sig_bytes(png_ptr, 8); // No sig png_read_info(png_ptr, info_ptr); png_uint_32 width, height; int bit_depth, color_type, interlace_type, compression_type, filter_method; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method); int rowbytes = png_get_rowbytes(png_ptr, info_ptr); unsigned char * row_pointers[height]; unsigned char * data = new unsigned char [rowbytes*height]; for (int i = 0; i<height; i++) row_pointers[i] = data + i*rowbytes; png_read_image(png_ptr, (png_byte **) row_pointers); png_read_end(png_ptr, NULL); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); loadhere->sprites[index].data = data; loadhere->sprites[index].width = width; loadhere->sprites[index].height = height; } fclose(fp); return true; } loadhere->type = 0; loadhere->total = total; loadhere->sprites = new sprite [total]; //if (! checkNew (loadhere->sprites)) return false; if (spriteBankVersion) { howmany = fgetc(fp); startIndex = 1; } totalwidth[0] = maxheight[0] = 0; for (i = 0; i < total; i ++) { switch (spriteBankVersion) { case 2: picwidth = get2bytes(fp); picheight = get2bytes(fp); loadhere->sprites[i].xhot = getSigned (fp); loadhere->sprites[i].yhot = getSigned (fp); break; default: picwidth = (unsigned char) fgetc(fp); picheight = (unsigned char) fgetc(fp); loadhere->sprites[i].xhot = fgetc(fp); loadhere->sprites[i].yhot = fgetc(fp); break; } if (totalwidth[numTextures] + picwidth < 2048) { loadhere->sprites[i].tex_x = totalwidth[numTextures]; totalwidth[numTextures] += (loadhere->sprites[i].width = picwidth); if ((loadhere->sprites[i].height = picheight) > maxheight[numTextures]) maxheight[numTextures] = picheight; } else { numTextures++; if (numTextures > 65535) return false;//fatal ("Can't open sprite bank / font - it's too big."); loadhere->sprites[i].tex_x = 0; totalwidth[numTextures] = (loadhere->sprites[i].width = picwidth); maxheight[numTextures] = loadhere->sprites[i].height = picheight; } loadhere->sprites[i].texNum = numTextures; loadhere->sprites[i].data = (unsigned char *) new unsigned char [picwidth * (picheight + 1)]; //if (! checkNew (data)) return false; int ooo = picwidth * picheight; for (int tt = 0; tt < picwidth; tt ++) { loadhere->sprites[i].data[ooo ++] = 0; } switch (spriteBankVersion) { case 2: // RUN LENGTH COMPRESSED DATA { unsigned size = picwidth * picheight; unsigned pip = 0; while (pip < size) { unsigned char col = fgetc(fp); int looper; if (col > howmany) { col -= howmany + 1; looper = fgetc(fp) + 1; } else looper = 1; while (looper --) { loadhere->sprites[i].data[pip ++] = col; } } } break; default: // RAW DATA size_t bytes_read = fread (loadhere->sprites[i].data, picwidth, picheight, fp); if (bytes_read != picwidth * picheight && ferror (fp)) { fprintf(stderr, "Reading error in loadSpriteBank.\n"); } break; } } numTextures++; if (! spriteBankVersion) { howmany = fgetc(fp); startIndex = fgetc(fp); } if (! reserveSpritePal (&loadhere->myPalette, howmany + startIndex)) return false; for (i = 0; i < howmany; i ++) { loadhere->myPalette.r[i + startIndex] = (unsigned char) fgetc(fp); loadhere->myPalette.g[i + startIndex] = (unsigned char) fgetc(fp); loadhere->myPalette.b[i + startIndex] = (unsigned char) fgetc(fp); loadhere->myPalette.pal[i + startIndex] = makeColour (loadhere->myPalette.r[i + startIndex], loadhere->myPalette.g[i + startIndex], loadhere->myPalette.b[i + startIndex]); } fclose(fp); return true; }
void App::on_getCostButton_clicked() { /*********************** double N = 18; double S = 95; double K = 100; double T = 1; double r = 0; double v0 = 0.04; double theta = 0.04; double kappa = 0.25; double sigma = 0.5; double rho = -0.6; ***********************/ // Проводим валидацию и считываем данные QString msg = ""; for (int i = 0; i < 9; i++) { if (!(*lines)[i]->hasAcceptableInput()) { msg += s->at(i) + ", "; } } msg.remove(msg.length() - 2, 2); if (!msg.isEmpty()) { msg += QString::fromLocal8Bit(" вне границ\n "); QMessageBox errorBox(QMessageBox::Critical, QString::fromLocal8Bit("Ошибка ввода"),msg,QMessageBox::Ok,this); errorBox.setInformativeText(QString::fromLocal8Bit("Подробнее в Помощь - \"ГРАНИЦЫ ПАРАМЕТРОВ\"")); errorBox.exec(); } else { N = ui.N_SpinBox->text().toInt(); data.S = ui.S_Line->text().toDouble(); data.K = ui.K_Line->text().toDouble(); data.T = ui.T_Line->text().toDouble(); data.r = ui.r_Line->text().toDouble(); data.v0 = ui.v0_Line->text().toDouble(); data.theta = ui.theta_Line->text().toDouble(); data.kappa = ui.kappa_Line->text().toDouble(); data.sigma = ui.sigma_Line->text().toDouble(); data.rho = ui.rho_Line->text().toDouble(); double price = callPriceFFT(N, data.S, data.K, data.T, data.r, data.v0, data.theta, data.kappa, data.sigma, data.rho); ui.Opt_Line->setText(QString::number(price)); } /* N = ui.N_SpinBox->text().toInt(); data.S = ui.S_Line->text().toDouble(); data.K = ui.K_Line->text().toDouble(); data.T = ui.T_Line->text().toDouble(); data.r = ui.r_Line->text().toDouble(); data.v0 = ui.v0_Line->text().toDouble(); data.theta = ui.theta_Line->text().toDouble(); data.kappa = ui.kappa_Line->text().toDouble(); data.sigma = ui.sigma_Line->text().toDouble(); data.rho = ui.rho_Line->text().toDouble(); bool *b = new bool[9]; QString msg = ""; b[0] = data.S > 0. & data.S <= 100000.; b[1] = data.K > 0. & data.K <= 100000.; b[2] = data.r >= 0. & data.r <= 1.; b[3] = data.T > 0. & data.T <= 3.; b[4] = data.v0 > 0. & data.v0 < 1.; b[5] = data.theta >= 0. & data.theta <= 1.; b[6] = data.kappa >= 0. & data.kappa <= 50.; b[7] = data.sigma > 0. & data.sigma < 1.; b[8] = data.rho >= -1. & data.rho <= 1.; if (!(b[0] && b[1] && b[2] && b[3] && b[4] && b[5] && b[6] && b[7] && b[8])) { QString temp = ""; for (int j = 0; j < 9; j++) { if (!b[j]) { temp += s[j] + ", "; } } temp.remove(temp.length() - 2, 2); msg += temp; msg += QString::fromLocal8Bit(" вне границ\n"); QMessageBox::StandardButton Load; Load = QMessageBox::critical(this, QString::fromLocal8Bit("Ошибка"), msg, QMessageBox::Ok); } else { double price = callPriceFFT(N, data.S, data.K, data.T, data.r, data.v0, data.theta, data.kappa, data.sigma, data.rho); ui.Opt_Line->setText(QString::number(price)); } delete b; */ }
SludgeApplication::SludgeApplication(const char * gladeFileName, const char * iconName, const char * configFile) { configfile = configFile; GError *err = NULL; initSuccess = TRUE; char buf[1000]; GdkPixbuf *pixbuf16, *pixbuf32, *pixbuf128, *pixbuf256; GList *list = NULL; sprintf(buf, "%s%s_16x16x32.png", DATADIR, iconName); pixbuf16 = gdk_pixbuf_new_from_file (buf, &err); if (err == NULL) { sprintf(buf, "%s%s_32x32x32.png", DATADIR, iconName); pixbuf32 = gdk_pixbuf_new_from_file (buf, &err); } if (err == NULL) { sprintf(buf, "%s%s_128x128x32.png", DATADIR, iconName); pixbuf128 = gdk_pixbuf_new_from_file (buf, &err); } if (err == NULL) { sprintf(buf, "%s%s_256x256x32.png", DATADIR, iconName); pixbuf256 = gdk_pixbuf_new_from_file (buf, &err); } if (err != NULL) { fprintf (stderr, "Unable to open icon file: %s\n", err->message); g_error_free (err); } else { list = g_list_append (list, pixbuf16); list = g_list_append (list, pixbuf32); list = g_list_append (list, pixbuf128); list = g_list_append (list, pixbuf256); gtk_window_set_default_icon_list(list); } /* * Load the GTK interface. */ theXml = gtk_builder_new (); if (!gtk_builder_add_from_file (theXml, gladeFileName, NULL)) { g_critical ("Failed to load the GTK file.\n"); errorBox("Error!", joinTwoStrings("Failed to load resource file:\n", gladeFileName)); initSuccess = FALSE; return; } /* * Get the top-level window reference from loaded Glade file. */ theWindow = GTK_WIDGET (gtk_builder_get_object (theXml, "window1")); if (theWindow == NULL) { g_critical ("Failed to get the window from the builder.\n"); initSuccess = FALSE; return; } // Set unassigned widgets to get handled automatically by the window manager. gtk_container_set_reallocate_redraws (GTK_CONTAINER (theWindow), TRUE); char folderFile[300]; sprintf(folderFile, "%s/sludge-devkit/%s", g_get_user_config_dir(), configfile); FILE * fp = fopen (folderFile, "r"); if (fp) { char readChar = ' '; for (int i = 0; i < 300; i++) { readChar = fgetc(fp); if (readChar != '\n') { currentFolder[i] = readChar; } else { currentFolder[i] = 0; break; } } fclose (fp); } else { sprintf (currentFolder, "%s", g_get_home_dir()); } fileChanged = FALSE; currentFilename[0] = 0; currentShortname[0] = 0; }
void Grid::train(bool skipTraining) { cout<<"********Grid::train init_: "<<init_<<endl; if ( _collection->getNumTracks() == 0 && trainFile_.length() == 0) { emit errorBox("Need to load a collection of audio files first!"); return; } // Read the feature matrix from file som_fmatrix.txt realvec norm_som_fmatrix; ifstream iss; iss.open("norm_som_fmatrix.txt"); iss >> norm_som_fmatrix; // Skip the SOM manipulation. if(!skipTraining) { if(init_) { ifstream iss1; iss1.open("som.mpl"); som_ = mng.getMarSystem(iss1); iss1.close(); som_->updctrl("mrs_natural/inSamples", norm_som_fmatrix.getCols()); } else { // Create netork for training the self-organizing map som_ = mng.create("SOM", "som"); som_->updctrl("mrs_natural/grid_width", som_width); som_->updctrl("mrs_natural/grid_height", som_height); som_->updctrl("mrs_natural/inSamples", norm_som_fmatrix.getCols()); som_->updctrl("mrs_natural/inObservations", norm_som_fmatrix.getRows()); } som_->updctrl("mrs_real/alpha_decay_train", train_alpha_); som_->updctrl("mrs_real/neighbourhood_decay_train", train_neighbourhood_); som_->updctrl("mrs_real/std_factor_train", train_std_factor_); som_->updctrl("mrs_string/mode", "train"); realvec som_fmatrixres; som_fmatrixres.create(som_->getctrl("mrs_natural/onObservations")->to<mrs_natural>(), som_->getctrl("mrs_natural/onSamples")->to<mrs_natural>()); ofstream oss1; oss1.open("som2.mpl"); oss1 << *som_; oss1.close(); cout << "Starting training" << endl; bool done_ = false; for (int i=0; i < train_iterations_; i ++) { if(cancel_) { cancel_ = false; done_ = false; break; } cout << "Training iteration" << i << endl; norm_som_fmatrix.shuffle(); som_->process(norm_som_fmatrix, som_fmatrixres); cout<<"x:"<<som_fmatrixres(0,0)<<"y:"<<som_fmatrixres(1,0)<<endl; done_ = true; } oss1.open("som3.mpl"); oss1 << *som_ << endl; oss1.close(); som_->updctrl("mrs_bool/done", done_); som_->tick(); cout << "Training done" << endl; // write the trained som network and the feature normalization networks oss1.open("som.mpl"); oss1 << *som_ << endl; delete som_; } }
/* Init works by extracting the dropped files, then trains the grid with them. The other files are then extracted and prediction is started. */ void Grid::init() { cout << "starting init" << endl; if (initFileLocations.size() != 0) { realvec* init_train_fmatrix = new realvec(); // make music.mf file of dropped files for(int i = 0; i < initFileLocations.size(); i++) { for (int l = 0; l < initFileLocations[i].size(); l++) { realvec temp; multimap<std::string, realvec>::iterator temp2 = normFeatureHash->find( initFileLocations[i].at(l)->getFileName() ); //check that temp has something, if it doesn't display error and abort if(temp2 == normFeatureHash->end()) { std::stringstream strStm; strStm << initFileLocations[i].at(l)->getFileName() << " was not extracted, please run Extract again"; emit errorBox(strStm.str().c_str()); return; } temp = temp2->second; //62 rows and cols equal to number of files... init_train_fmatrix->stretch( temp.getRows() + 2, init_train_fmatrix->getCols() + temp.getCols() ); for(int j = 0; j < temp.getRows(); j++) { //copy features over from temp into init_train_matrix cell by cell (*init_train_fmatrix)(j, init_train_fmatrix->getCols() -1 ) = temp(j,0); } // add X and Y position info to the last two rows of the vector (*init_train_fmatrix)(temp.getRows(), init_train_fmatrix->getCols() -1 ) = initFileLocations[i].at(l)->getX(); (*init_train_fmatrix)(temp.getRows() + 1, init_train_fmatrix->getCols() -1 ) = initFileLocations[i].at(l)->getY(); } } ofstream oss1; oss1.open("init_train_fmatrix.mpl"); oss1 << *init_train_fmatrix << endl; oss1.close(); init_ = true; som_ = mng.create("SOM", "som"); som_->updctrl("mrs_natural/grid_width", som_width); som_->updctrl("mrs_natural/grid_height", som_height); som_->updctrl("mrs_natural/inSamples", init_train_fmatrix->getCols());//number of files som_->updctrl("mrs_natural/inObservations", init_train_fmatrix->getRows()); //calls update() in SOM.cpp som_->updctrl("mrs_string/mode", "init"); som_->updctrl("mrs_real/alpha_decay_init", init_alpha_); som_->updctrl("mrs_real/neighbourhood_decay_init", init_neighbourhood_); som_->updctrl("mrs_real/std_factor_init", init_std_factor_); realvec som_fmatrixres; som_fmatrixres.create(som_->getctrl("mrs_natural/onObservations")->to<mrs_natural>(), som_->getctrl("mrs_natural/onSamples")->to<mrs_natural>()); // loop this for more init runs for (int i = 0; i < init_iterations_; i++) { init_train_fmatrix->shuffle(); som_->process(*init_train_fmatrix, som_fmatrixres); } //som_->tick(); som_->updctrl("mrs_bool/done", true); // write the trained som network and the feature normalization networks oss1.open("som.mpl"); oss1 << *som_; oss1.close(); oss1.open("som1.mpl"); oss1 << *som_; oss1.close(); cout << "end of init" << endl; } else { emit errorBox("Need to drop files for initilization!"); } }
void Grid::predict() { int ready = 0; std: string fileName; if ( _collection->getNumTracks() > 0 ) { ready = 1; fileName = "margrid_train.mf"; } else if (trainFile_.length() > 0) { fileName = trainFile_; } else { emit errorBox("Need to load a collection of audio files first!"); return; } realvec som_in; realvec som_res; realvec som_res1; realvec som_fmatrix; QDir dir; ifstream iss1; iss1.open("som.mpl"); som_ = mng.getMarSystem(iss1); iss1.close(); ifstream niss1; niss1.open("norm.mpl"); norm_ = mng.getMarSystem(niss1); niss1.close(); cout << "Starting prediction" << endl; som_->updctrl("mrs_string/mode", "predict"); Collection l1; l1.read(fileName); cout << "Read collection" << endl; total_->updctrl("mrs_string/filename", fileName); total_->updctrl("mrs_natural/pos", 0); som_->updctrl("mrs_natural/inSamples", 1); realvec predict_res(som_->getctrl("mrs_natural/onObservations")->to<mrs_natural>(), som_->getctrl("mrs_natural/onSamples")->to<mrs_natural>()); norm_->updctrl("mrs_natural/inSamples", 1); realvec norm_som_res; mrs_natural inObs = total_->getctrl("mrs_natural/inObservations")->to<mrs_natural>(); mrs_natural inSms = total_->getctrl("mrs_natural/inSamples")->to<mrs_natural>(); mrs_natural onObs = total_->getctrl("mrs_natural/onObservations")->to<mrs_natural>(); mrs_natural onSms = total_->getctrl("mrs_natural/onSamples")->to<mrs_natural>(); som_in.create(inObs, inSms); som_res.create(onObs, onSms); som_res1.create(onObs+2, onSms); norm_som_res.create(onObs+2, onSms); ofstream oss1; oss1.open("som4.mpl"); oss1 << *som_ << endl; oss1.close(); realvec norm_som_fmatrix; ifstream iss; iss.open("norm_som_fmatrix.txt"); iss >> norm_som_fmatrix; cout << l1.size() <<endl; QString tempString; for (int index = 0; index < l1.size(); index++) { if(cancel_) { cancel_ = false; break; } total_->updctrl("mrs_natural/label", index); total_->updctrl("mrs_bool/memReset", true); total_->updctrl("mrs_natural/cindex", index); total_->process(som_in, som_res); for (int o=0; o < onObs; o++) som_res1(o, 0) = som_res(o, 0); QString current = total_->getctrl("mrs_string/currentlyPlaying")->to<mrs_string>().c_str(); cout << total_->getctrl("mrs_string/currentlyPlaying")->to<mrs_string>() << endl; norm_->process(som_res1, norm_som_res); realvec foobar; foobar.create(som_->getctrl("mrs_natural/inObservations")->to<mrs_natural>(), som_->getctrl("mrs_natural/inSamples")->to<mrs_natural>()); norm_som_fmatrix.getCol(index, foobar); som_->process(foobar, predict_res); grid_x = predict_res(0); grid_y = predict_res(1); addTrack(grid_x, grid_y, current); emit repaintSignal(); total_->updctrl("mrs_natural/advance", 1); } cout << "end_prediction" << endl; }