void ModoGraficoSDL::actualizar() { SDL_RenderPresent(this->renderizador); }
int main(int argc, const char *argv[]) { if(argc != 2) { printf("%s takes .ttf file as argument.\n", argv[0]); return 1; } SDL_version compile_version; const SDL_version *link_version=TTF_Linked_Version(); SDL_TTF_VERSION(&compile_version); printf("compiled with SDL_ttf version: %d.%d.%d\n", compile_version.major, compile_version.minor, compile_version.patch); printf("running with SDL_ttf version: %d.%d.%d\n", link_version->major, link_version->minor, link_version->patch); if(SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("Error with import!\n"); return 1; } SDL_Window *win = SDL_CreateWindow( "TTF Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN); SDL_Renderer *renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(TTF_Init() == -1) { printf("Error loading TTF_Init()!\n%s\n", TTF_GetError()); SDL_Quit(); exit(2); } TTF_Font *font; /* MS Himalaya (himalaya.ttf): http://fontzone.net/font-details/microsoft-himalaya */ font = TTF_OpenFont(argv[1], 600); if(!font) { printf("%s\n", TTF_GetError()); return 1; } const char tibstring[] = { 0xe0, 0xbd, 0x96, 0xe0, 0xbd, 0xa6, 0xe0, 0xbe, 0x90, 0xe0, 0xbe, 0xb1, 0xe0, 0xbd, 0xbc, 0xe0, 0xbd, 0x84, 0xe0, 0xbd, 0xa6 }; SDL_Color colour = { 255, 255, 255, 255 }; SDL_Surface *surface = TTF_RenderUTF8_Solid(font, tibstring, colour); if(surface == NULL) { TTF_CloseFont(font); printf("Surface error!\n"); return 0; } SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_Event event; int quit = 0; while (!quit) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) quit = 1; } SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } TTF_CloseFont(font); SDL_Quit(); return 0; }
int main(int argc, char *args[]) { SDL_Init(SDL_INIT_EVERYTHING); //Init SDL Mix_Init(MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG); //Init SDL Mixer Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096); //Open audiostream int temp = officalDelay; //The delay it will play int holder = -1; //Hold which sound it played before int counter = 0; //How many soundclips have been played //Create window and check if it's loaded SDL_Window *win = SDL_CreateWindow("Omvand Synestesi", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 800, SDL_WINDOW_SHOWN); if (win == NULL) { std::cout << "Couldn't create window, unkown error." << std::endl; } //Make a renderer SDL_Renderer *renderer = SDL_CreateRenderer(win, 0, SDL_RENDERER_ACCELERATED); //Create a texture, load it. Check if it's loaded SDL_Texture *texture = load_texture("get.bmp", renderer); if(texture == NULL) { std::cout << "Couldn't load picture, check so it's named get.bmp" << std::endl; } //Loads a surface, this is the picture it will take and make sound of. SDL_Surface *image = SDL_LoadBMP("get.bmp"); if (image == NULL) { std::cout << "Couldn't load picture until surface. Check the name so it is get.bmp" << std::endl; } //Load soundfiles Mix_Music *sound[15]; for (int i = 1; i < 16; i++) { std::string path = "sound/get" + convertInt(i) + ".wav"; sound[i] = Mix_LoadMUS(path.c_str()); std::cout << "Loaded soundfile: " << path << std::endl; if (sound[i] == NULL) { std::cout << "Couldn't load soundfile " << path << ". Check so the name is get" << i << ".wav" << std::endl; } } //Loop through the whole picture for (int y = 0; y < size_h; y++) { for (int x = 0; x < size_w; x++) { Uint32 pix = getPixel(image, x, y); SDL_RenderClear(renderer); //Clear the screen SDL_RenderCopy(renderer, texture, NULL, NULL); //Print out the picture SDL_RenderPresent(renderer); //Actually render the picture int npix = pix % 16 + 1; //Get's a value from the pixel and makes it so it's just 1 to 16 std::cout << "!-- " << pix << " --! " << npix << " | " << counter << "/1296" << std::endl; //Prints out some stuff so you can see for debugging mostly //If the same value is again, make a longer delay before playing next song, and if not, go back to standard delay if (npix == holder) { temp = temp + 120; } else { temp = officalDelay; } //Play right soundfile from value of pixel for (int i = 1; i < 15; i++) { int newi = i + 1; if (i == npix) { Mix_PlayMusic(sound[newi], 0); SDL_Delay(temp); holder = i; } } //If value is 16, don't play a sound and make a 3sec long delay. if (npix == 16) { std::cout << std::endl << "-----" << std::endl << std::endl; SDL_Delay(3000); } counter++; } } SDL_FreeSurface(image); SDL_DestroyRenderer(renderer); SDL_DestroyTexture(texture); SDL_DestroyWindow(win); for (int i = 1; i < 16; i++) { Mix_FreeMusic(sound[i]); } Mix_Quit(); SDL_Quit(); return 0; }
void Window::renderUI() { SDL_RenderCopy(renderer, textures[UI], NULL, &dstRects[UI]); SDL_RenderPresent(renderer); }
void Graphics::flip() { SDL_RenderPresent(this->_renderer); }
void Game::render() { SDL_SetRenderDrawColor(_renderer, r, g, b, 0); SDL_RenderClear(_renderer); SDL_RenderPresent(_renderer); }
int Application::exec() { bool done = false; while (!done) { SDL_Event e; if (SDL_WaitEvent(&e)) { switch (e.type) { case SDL_WINDOWEVENT: { Widget *w = widgetByWindowId(e.window.windowID); switch (e.window.event) { case SDL_WINDOWEVENT_SHOWN: std::cout << "Window " << e.window.windowID << " shown" << std::endl; break; case SDL_WINDOWEVENT_HIDDEN: std::cout << "Window " << e.window.windowID << " hidden" << std::endl; break; case SDL_WINDOWEVENT_EXPOSED: { needUpdateWithoutRedraw_ = w; break; } case SDL_WINDOWEVENT_MOVED: break; case SDL_WINDOWEVENT_RESIZED: { w->resize(e.window.data1, e.window.data2); #if __APPLE__==1 SDL_RenderPresent(w->renderer_); // hack for MacOS X #endif break; } case SDL_WINDOWEVENT_MINIMIZED: std::cout << "Window " << e.window.windowID << " minimized" << std::endl; break; case SDL_WINDOWEVENT_MAXIMIZED: std::cout << "Window " << e.window.windowID << " maximized" << std::endl; break; case SDL_WINDOWEVENT_RESTORED: std::cout << "Window " << e.window.windowID << " restored" << std::endl; break; case SDL_WINDOWEVENT_ENTER: std::cout << "Mouse entered window " << e.window.windowID << std::endl; break; case SDL_WINDOWEVENT_LEAVE: std::cout << "Mouse left window " << e.window.windowID << std::endl; break; case SDL_WINDOWEVENT_FOCUS_GAINED: std::cout << "Window " << e.window.windowID << " gained keyboard focus" << std::endl; break; case SDL_WINDOWEVENT_FOCUS_LOST: std::cout << "Window " << e.window.windowID << " lost keyboard focus" << std::endl; break; case SDL_WINDOWEVENT_CLOSE: std::cout << "Window " << e.window.windowID << " closed" << std::endl; break; default: std::cout << "Window " << e.window.windowID << " got unknown event " << static_cast<int>(e.window.event) << std::endl; break; } break; } case SDL_KEYDOWN: { KeyEvent ke { static_cast<KeyEvent::Key>(e.key.keysym.sym), SDL_GetModState(), static_cast<bool>(e.key.repeat) }; auto w = focusWidget(); if (!w) w = widgetByWindowId(e.key.windowID); else if (w->ancestor() != widgetByWindowId(e.key.windowID)) { std::cerr << "Unknown windowID " << e.key.windowID << std::endl; break; } while (w) { if (w->keyPressEvent(ke)) break; w = w->parent(); } break; } case SDL_KEYUP: { KeyEvent ke { static_cast<KeyEvent::Key>(e.key.keysym.sym), SDL_GetModState(), static_cast<bool>(e.key.repeat) }; auto w = focusWidget(); if (!w) w = widgetByWindowId(e.key.windowID); else if (w->ancestor() != widgetByWindowId(e.key.windowID)) { std::cerr << "Unknown windowID " << e.key.windowID << std::endl; break; } while (w) { if (w->keyReleaseEvent(ke)) break; w = w->parent(); } break; } case SDL_TEXTINPUT: { TextInputEvent tie { toUtf16(e.text.text) }; auto w = focusWidget(); if (!w) w = widgetByWindowId(e.key.windowID); else if (w->ancestor() != widgetByWindowId(e.key.windowID)) { std::cerr << "Unknown windowID " << e.key.windowID << std::endl; break; } while (w) { if (w->textInputEvent(tie)) break; w = w->parent(); } break; } case SDL_QUIT: done = true; break; } } const auto isEmpty = (SDL_PeepEvents(&e, 1, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) == 0); if (isEmpty || SDL_GetTicks() > lastUpdate_ + 1000 / 60) { auto x = SDL_GetTicks(); for (auto w: widgetList_) if (w->needRepaint()) { PaintEvent e; w->internalPaint(e); } if (needUpdateWithoutRedraw_) { needUpdateWithoutRedraw_->updateWithoutRedraw(); needUpdateWithoutRedraw_ = nullptr; } lastUpdate_ = SDL_GetTicks(); std::cout << "Update time: " << lastUpdate_ - x << " " << (lastUpdate_ - x > 0 ? 1000 / (lastUpdate_ - x) : 999)<< "fps" << std::endl; } for (auto obj: deletingObjects_) delete obj; deletingObjects_.clear(); } return 0; }
std::vector<Landmark> createLandmarks() { std::vector<Landmark> lmks; SDL_Color color_red = {.r = 255, .g = 0, .b = 0, .a = 255 }; SDL_Color color_green = {.r = 0, .g = 255, .b = 0, .a = 255 }; SDL_Color color_blue = {.r = 0, .g = 0, .b = 255, .a = 255 }; SDL_Color color_purple = {.r = 255, .g = 0, .b = 255, .a = 255 }; lmks.push_back( Landmark(300.,300.,color_red)); lmks.push_back( Landmark(124.,478.,color_blue)); // lmks.push_back( Landmark(214.,312.,color_purple)); return lmks; } int main() { if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } SDL_Window *win = SDL_CreateWindow("Robot Program", XSTART, YSTART, WWIDTH, WHEIGHT, SDL_WINDOW_SHOWN); if (win == nullptr){ std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr){ SDL_DestroyWindow(win); std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } std::vector<Landmark> landmarks = createLandmarks(); SDL_Color orange {.r=255, .g=165, .b=0, .a=255}; SDL_Color red {.r=255, .g=0, .b=0, .a=255}; SDL_Color gray {.r=128, .g=128, .b=128, .a=255}; Robot robby(200, 200, 0.0, 20, red); // Kalman filter stuff int n = 3; // number of state variables (x,y,phi) int m = 3; // number of measurements (landmark x, y, index) // Best guess of initial states Eigen::VectorXf x0(n); //[x, y, phi] x0 << 200., 200., 0.0; Robot robby_estimate(x0(0), x0(1), x0(2), 18, gray); // control vector: Eigen::VectorXf control(2); // [v, omega] Eigen::MatrixXf A(n, n); // System dynamics matrix Eigen::MatrixXf C(m, n); // Output matrix Eigen::MatrixXf Q(n, n); // Process noise covariance Eigen::MatrixXf R(m, m); // Measurement noise covariance Eigen::MatrixXf covariance(n, n); // Estimate error covariance // Reasonable covariance matrices covariance << 5., .0, .0, .0, 5., .0, .0, .0, 5.; R << 1.0, 0., 0., 0., 1.0, 0., 0., 0., 0.1; Q << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1; KalmanFilter kf(DT, A, C, Q, R, covariance); float t0 = 0.0; kf.init(t0, x0); // rendering loop int i = 0; while (i < 10000) { //First clear the renderer SDL_RenderClear(ren); //Draw the texture SDL_SetRenderDrawColor(ren, 200, 200, 255, 255); SDL_RenderClear(ren); // fill the scene with white SDL_SetRenderDrawColor(ren, 0, 0, 0, 255); // update renderer SDL_RenderPresent(ren); // move robot SDL_PumpEvents(); const Uint8 *key_pressed = SDL_GetKeyboardState(NULL); robby.move(key_pressed, control); // measure landmark positions auto observed_landmarks = robby.measureLandmarks(landmarks); // get robot state Eigen::VectorXf state = robby.get_state(); // Localize via Landmarks kf.localization_landmarks(observed_landmarks, landmarks, control); // get estimated state (x,y,phi) as estimated by the EKF auto x_hat = kf.get_state(); printf("True x,y,phi: %f, %f, %f\n", state(0), state(1),state(2)); printf("Estimated x,y,phi: %f, %f, %f\n", x_hat(0), x_hat(1), x_hat(2)); // move robby estimate to new pose as calculated by kalman filter: robby_estimate.setPose(x_hat(0), x_hat(1), x_hat(2)); robby_estimate.render(ren); // render robot robby.render(ren); // render landmarks for (auto lm = landmarks.begin(); lm != landmarks.end(); ++lm) { SDL_SetRenderDrawColor(ren, lm->id.r, lm->id.g, lm->id.b, lm->id.a); lm->render(ren); } SDL_SetRenderDrawColor(ren, gray.r, gray.g, gray.b, gray.a); // render sampled probability distribution kf.renderSamples(ren); SDL_RenderPresent(ren); //Take a quick break after all that hard work SDL_Delay(30); if (key_pressed[SDL_SCANCODE_RETURN]) { printf("Exiting Program!\n"); break; } i+=1; } SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; }
int main(){ TempSettings gamesettings; gamesettings.mapw = 10; gamesettings.maph = 6; gamesettings.mapx = 0; gamesettings.mapy = 0; gamesettings.mapmidx = gamesettings.mapw/2.0; gamesettings.mapmidy = gamesettings.maph/2.0; gamesettings.window_width = 1300; gamesettings.window_height = 800; // initialize window, renderer, textures if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl; return 1; } if (TTF_Init() != 0){ std::cerr << "TTF_Init error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Window* window = SDL_CreateWindow("deathblade_floating", 0, 0, gamesettings.window_width, gamesettings.window_height, SDL_WINDOW_SHOWN); if (window == nullptr){ std::cerr << "SDL_CreateWindow error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == nullptr){ std::cerr << "SDL_CreateRenderer error: " << SDL_GetError() << std::endl; SDL_DestroyWindow(window); SDL_Quit(); return 1; } std::string resource_path = getResourcePath(""); std::string charfile = resource_path + "initialcharacter.png"; std::string bgfile = resource_path + "initialbackgroundtile.png"; std::string starfile = resource_path + "star.png"; std::string wallfile = resource_path + "wall.png"; SDL_Texture* character_texture = IMG_LoadTexture(renderer, charfile.c_str()); SDL_Texture* bgtile_texture = IMG_LoadTexture(renderer, bgfile.c_str()); SDL_Texture* star_texture = IMG_LoadTexture(renderer, starfile.c_str()); SDL_Texture* wall_texture = IMG_LoadTexture(renderer,wallfile.c_str()); if (character_texture == nullptr || bgtile_texture == nullptr || star_texture == nullptr || wall_texture == nullptr){ std::cerr << "IMG_LoadTexture error: " << SDL_GetError() << std::endl; SDL_DestroyTexture(character_texture); SDL_DestroyTexture(bgtile_texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 1; } std::string fontfile = resource_path + "sample.ttf"; TTF_Font* font = TTF_OpenFont(fontfile.c_str(), 15); if (font == NULL){ std::cerr << "TTF_OpenFont error: " << SDL_GetError() << std::endl; } CameraControl camera(&gamesettings); ObjectController objects; DeveloperConsoleClass console(&gamesettings); console.add_controller(&console); console.add_controller(&camera); const double tilew = 0.5; const double tileh = 0.5; double mousex = gamesettings.mapmidx; double mousey = gamesettings.mapmidy; int mousepx = gamesettings.window_width/2; int mousepy = gamesettings.window_height/2; double wallthickness = 0.1; TextureWall bottomwall, topwall, leftwall, rightwall; bottomwall.x = gamesettings.mapw/2; bottomwall.y = gamesettings.maph+wallthickness/2; bottomwall.setTexture(wall_texture,gamesettings.mapw,wallthickness); objects.add_object(&bottomwall); topwall.x = gamesettings.mapw/2; topwall.y = -wallthickness/2; topwall.setTexture(wall_texture,gamesettings.mapw,wallthickness); objects.add_object(&topwall); leftwall.x = -wallthickness/2; leftwall.y = gamesettings.maph/2; leftwall.setTexture(wall_texture,wallthickness,gamesettings.maph); objects.add_object(&leftwall); rightwall.x = gamesettings.mapw + wallthickness/2; rightwall.y = gamesettings.maph/2; rightwall.setTexture(wall_texture,wallthickness,gamesettings.maph); objects.add_object(&rightwall); Player human; human.x = 5; human.y = 5; human.dx = -0.025; human.dy = -0.03; human.setTexture(character_texture, 0.05, 0.05); objects.add_object(&human); // map x [0, 10] // map y [0, 6] // star width 0.256 std::vector<vec2d> star_positions = { vec2d(6,4), vec2d(3,4.1), vec2d(9,0.2), vec2d(1,0.4), vec2d(2,2.5), vec2d(3,2.5), vec2d(9,4.9), vec2d(0.2,5.1), vec2d(4.1,4.1) }; std::vector<double> star_thetas = { 0, 45, 15, 60, 85, 4, 50, 66, 31 }; std::vector<Star*> star_field; for(unsigned int i = 0; i < star_positions.size(); ++i){ Star* newstar = new Star(); newstar->x = star_positions[i].x; newstar->y = star_positions[i].y; newstar->setTexture(star_texture, 0.256, 0.256); if(i < star_thetas.size()) newstar->rotate(star_thetas[i]*3.14159265359/180.0); star_field.push_back(newstar); objects.add_object(star_field[i]); } bool rightmouse_down = false; SDL_Event event; bool quitnow = false; Uint32 fps_lastframe = SDL_GetTicks(); while(!quitnow){ int zoomdirection = 0; while(SDL_PollEvent(&event)){ if (console.is_active()){ if (event.type == SDL_KEYDOWN){ switch(event.key.keysym.sym){ case SDLK_BACKQUOTE: console.toggle(); break; case SDLK_BACKSPACE: console.backspace(); break; case SDLK_RETURN: case SDLK_RETURN2: console.enter(); break; case SDLK_UP: console.goback_inhistory(); break; case SDLK_DOWN: console.goforward_inhistory(); break; default: break; } console.render_current_command(renderer); } else if (event.type == SDL_TEXTINPUT && event.text.text[0] != '`'){ console.addinput(event.text.text); console.render_current_command(renderer); } else if (event.type == SDL_MOUSEBUTTONDOWN){ if (event.button.button == SDL_BUTTON_LEFT){ if(!console.mouse_grab(true, event.button.x, event.button.y)) camera.mousecontrol_on(); } //if (event.button.button == SDL_BUTTON_RIGHT) } else if (event.type == SDL_MOUSEBUTTONUP){ if (event.button.button == SDL_BUTTON_LEFT){ console.mouse_grab(false, -1,-1); camera.mousecontrol_off(); } } else if (event.type == SDL_MOUSEMOTION){ mousepx = event.motion.x; mousepy = event.motion.y; console.handle_mouse(event.motion.xrel, event.motion.yrel); if (camera.mouse_controlling()){ camera.mousecontrol_move(mousepx, mousepy, event.motion.xrel, event.motion.yrel,SDL_GetModState()==KMOD_LCTRL); } else{ mousex = camera.xfrompixel(event.motion.x, event.motion.y, db::Player); mousey = camera.yfrompixel(event.motion.x, event.motion.y, db::Player); } } else if (event.type == SDL_MOUSEWHEEL){ if(!console.scroll(event.wheel.y, mousepx, mousepy)) zoomdirection += event.wheel.y; } else if (event.type == SDL_QUIT){ quitnow = true; } continue; } // if console is not up if (event.type == SDL_KEYDOWN){ switch(event.key.keysym.sym){ case SDLK_ESCAPE: quitnow = true; break; case SDLK_BACKQUOTE: console.toggle(); break; case SDLK_t: if (!camera.is_tracking()) camera.track_object(&(human.x), &(human.y)); else camera.stop_tracking(); break; case SDLK_w: case SDLK_UP: camera.pan_updown(-1); break; case SDLK_a: case SDLK_LEFT: camera.pan_leftright(-1); break; case SDLK_s: case SDLK_DOWN: camera.pan_updown(1); break; case SDLK_d: case SDLK_RIGHT: camera.pan_leftright(1); break; default: break; } } else if (event.type == SDL_KEYUP){ switch(event.key.keysym.sym){ case SDLK_w: case SDLK_UP: camera.pan_updown(0); break; case SDLK_a: case SDLK_LEFT: camera.pan_leftright(0); break; case SDLK_s: case SDLK_DOWN: camera.pan_updown(0); break; case SDLK_d: case SDLK_RIGHT: camera.pan_leftright(0); break; default: break; } } else if (event.type == SDL_MOUSEBUTTONDOWN){ if (event.button.button == SDL_BUTTON_LEFT){ camera.mousecontrol_on(); } else if (event.button.button == SDL_BUTTON_RIGHT){ rightmouse_down = true; human.bound.xclick = camera.xfrompixel(event.button.x,event.button.y,db::Player); human.bound.yclick = camera.yfrompixel(event.button.x,event.button.y,db::Player); human.bound.xdrag = 0; human.bound.ydrag = 0; human.bound.enabled = true; } } else if (event.type == SDL_MOUSEBUTTONUP){ if (event.button.button == SDL_BUTTON_LEFT){ camera.mousecontrol_off(); } else if (event.button.button == SDL_BUTTON_RIGHT){ rightmouse_down = false; } } else if (event.type == SDL_MOUSEWHEEL){ zoomdirection += event.wheel.y; } else if (event.type == SDL_MOUSEMOTION){ mousepx = event.motion.x; mousepy = event.motion.y; if (camera.mouse_controlling()){ camera.mousecontrol_move(mousepx, mousepy, event.motion.xrel, event.motion.yrel,SDL_GetModState()==KMOD_LCTRL); } else{ mousex = camera.xfrompixel(event.motion.x, event.motion.y, db::Player); mousey = camera.yfrompixel(event.motion.x, event.motion.y, db::Player); if(mousepx <= 1) camera.pan_leftright(-1); else if (mousepx >= (int)gamesettings.window_width-1) camera.pan_leftright(1); else if (mousepx - event.motion.xrel <= 1) camera.pan_leftright(0); else if (mousepx - event.motion.xrel >= (int)gamesettings.window_width-1) camera.pan_leftright(0); if(mousepy <= 1) camera.pan_updown(-1); else if (mousepy >= (int)gamesettings.window_height-1) camera.pan_updown(1); else if (mousepy - event.motion.yrel <= 1) camera.pan_updown(0); else if (mousepy - event.motion.yrel >= (int)gamesettings.window_height-1) camera.pan_updown(0); if(rightmouse_down){ human.bound.xdrag += event.motion.xrel; human.bound.ydrag += event.motion.yrel; } } } else if (event.type == SDL_QUIT){ quitnow = true; } } objects.step_time(); SDL_SetRenderDrawColor(renderer, 0,0,0,255); SDL_RenderClear(renderer); camera.adjust_zoom(zoomdirection, mousex, mousey); for (double x = gamesettings.mapx+tilew/2; x < gamesettings.mapx+gamesettings.mapw+tilew/2; x += tilew){ for (double y = gamesettings.mapy+tileh/2; y < gamesettings.mapy+gamesettings.maph+tileh/2; y += tileh){ SDL_Rect dst = camera.calculate_display_destination(x,y,tilew,tileh,db::Floor); SDL_RenderCopyEx(renderer, bgtile_texture, NULL, &dst, -camera.camyaw*180.0/3.14156033, NULL, SDL_FLIP_NONE); } } objects.drawon(renderer, &camera); if(console.is_active()) console.drawon(renderer); human.bound.drawon(renderer, &camera); Uint32 fps_newframe = SDL_GetTicks(); if((fps_newframe-fps_lastframe) < SCREEN_TICKS_PER_FRAME){ SDL_Delay(SCREEN_TICKS_PER_FRAME - (fps_newframe-fps_lastframe)); } draw_fps(renderer, font, 1.0/(fps_newframe/1000.0 - fps_lastframe/1000.0)); fps_lastframe = fps_newframe; SDL_RenderPresent(renderer); } SDL_DestroyTexture(character_texture); SDL_DestroyTexture(bgtile_texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); for(unsigned int i = 0; i < star_field.size(); ++i) delete star_field[i]; return 0; }
void render(Scene& scene, Texture& screen, int renderno = 0, int outof = 1) { char titlebuf[200]; if (settings.show_preview) { sprintf(titlebuf, "%s", TITLE); SDL_SetWindowTitle(window, titlebuf); } Vect4 color; bool exitflag = 0; int v; //Return value from threads RenderQueue rq(&scene, &screen); SDL_Thread** threads = new SDL_Thread* [settings.nworkers]; rq.pushRow(0); for (int i = 0; i < settings.nworkers; i++) threads[i] = SDL_CreateThread(&renderThread, NULL, &rq); for (int i = 0; i < settings.nworkers; i++) SDL_WaitThread(threads[i], &v); for (int r = 1; r < screen.height(); r++) { if (settings.show_preview) { SDL_Event event; while (SDL_PollEvent(&event)) if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) exit(0); else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN) exitflag = 1; if (exitflag) break; } rq.pushRow(r); for (int i = 0; i < settings.nworkers; i++) threads[i] = SDL_CreateThread(&renderThread, NULL, &rq); if (settings.show_preview) { drawRow(screen, r - 1); px->redraw(); SDL_RenderPresent(px->getRenderer()); } for (int i = 0; i < settings.nworkers; i++) SDL_WaitThread(threads[i], &v); if (outof > 1) sprintf(titlebuf, "%s [%d / %d, %d of %d]",TITLE, r + 1, screen.height(), renderno, outof); else sprintf(titlebuf, "%s [%d / %d]", TITLE, r + 1, screen.height()); if (settings.show_preview) SDL_SetWindowTitle(window, titlebuf); else { printf("\r%s", titlebuf); fflush(0); } } if (settings.show_preview) { drawRow(screen, screen.height() - 1); px->redraw(); SDL_RenderPresent(px->getRenderer()); } else printf("\n"); if (!settings.aa_enabled) { delete [] threads; return; } Texture dmap = screen.differenceMap(); float d; for (int r = 1; r < screen.height() - 1; r++) { if (settings.show_preview) { SDL_Event event; while (SDL_PollEvent(&event)) if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) exit(0); else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN) exitflag = 1; if (exitflag) break; } for (int c = 1; c < screen.width() - 1; c++) { d = dot(dmap.getColor(r, c), Vect4(1, 1, 1, 0)); if (d > settings.aa_threshold) rq.push(r, c); } for (int i = 0; i < settings.nworkers; i++) threads[i] = SDL_CreateThread(&renderThread_AA, NULL, &rq); if (settings.show_preview) { drawRow(screen, r - 1); px->redraw(); SDL_RenderPresent(px->getRenderer()); } for (int i = 0; i < settings.nworkers; i++) SDL_WaitThread(threads[i], &v); if (outof > 1) sprintf(titlebuf, "%s [AA: %d / %d, %d of %d]", TITLE, r + 2, screen.height(), renderno, outof); else sprintf(titlebuf, "%s [AA: %d / %d]",TITLE, r + 2, screen.height()); if (settings.show_preview) SDL_SetWindowTitle(window, titlebuf); else { printf("\r%s", titlebuf); fflush(0); } } delete [] threads; if (settings.show_preview) { drawRow(screen, screen.height() - 2); px->redraw(); SDL_RenderPresent(px->getRenderer()); SDL_SetWindowTitle(window, TITLE); } else printf("\n"); }
int vid_thread (void* arg) { SDL_Event event; static char *eventtypes[SDL_LASTEVENT]; static t_bool initialized = FALSE; if (!initialized) { initialized = TRUE; eventtypes[SDL_QUIT] = "QUIT"; /**< User-requested quit */ /* These application events have special meaning on iOS, see README-ios.txt for details */ eventtypes[SDL_APP_TERMINATING] = "APP_TERMINATING"; /**< The application is being terminated by the OS Called on iOS in applicationWillTerminate() Called on Android in onDestroy() */ eventtypes[SDL_APP_LOWMEMORY] = "APP_LOWMEMORY"; /**< The application is low on memory, free memory if possible. Called on iOS in applicationDidReceiveMemoryWarning() Called on Android in onLowMemory() */ eventtypes[SDL_APP_WILLENTERBACKGROUND] = "APP_WILLENTERBACKGROUND"; /**< The application is about to enter the background Called on iOS in applicationWillResignActive() Called on Android in onPause() */ eventtypes[SDL_APP_DIDENTERBACKGROUND] = "APP_DIDENTERBACKGROUND"; /**< The application did enter the background and may not get CPU for some time Called on iOS in applicationDidEnterBackground() Called on Android in onPause() */ eventtypes[SDL_APP_WILLENTERFOREGROUND] = "APP_WILLENTERFOREGROUND"; /**< The application is about to enter the foreground Called on iOS in applicationWillEnterForeground() Called on Android in onResume() */ eventtypes[SDL_APP_DIDENTERFOREGROUND] = "APP_DIDENTERFOREGROUND"; /**< The application is now interactive Called on iOS in applicationDidBecomeActive() Called on Android in onResume() */ /* Window events */ eventtypes[SDL_WINDOWEVENT] = "WINDOWEVENT"; /**< Window state change */ eventtypes[SDL_SYSWMEVENT] = "SYSWMEVENT"; /**< System specific event */ /* Keyboard events */ eventtypes[SDL_KEYDOWN] = "KEYDOWN"; /**< Key pressed */ eventtypes[SDL_KEYUP] = "KEYUP"; /**< Key released */ eventtypes[SDL_TEXTEDITING] = "TEXTEDITING"; /**< Keyboard text editing (composition) */ eventtypes[SDL_TEXTINPUT] = "TEXTINPUT"; /**< Keyboard text input */ /* Mouse events */ eventtypes[SDL_MOUSEMOTION] = "MOUSEMOTION"; /**< Mouse moved */ eventtypes[SDL_MOUSEBUTTONDOWN] = "MOUSEBUTTONDOWN"; /**< Mouse button pressed */ eventtypes[SDL_MOUSEBUTTONUP] = "MOUSEBUTTONUP"; /**< Mouse button released */ eventtypes[SDL_MOUSEWHEEL] = "MOUSEWHEEL"; /**< Mouse wheel motion */ /* Joystick events */ eventtypes[SDL_JOYAXISMOTION] = "JOYAXISMOTION"; /**< Joystick axis motion */ eventtypes[SDL_JOYBALLMOTION] = "JOYBALLMOTION"; /**< Joystick trackball motion */ eventtypes[SDL_JOYHATMOTION] = "JOYHATMOTION"; /**< Joystick hat position change */ eventtypes[SDL_JOYBUTTONDOWN] = "JOYBUTTONDOWN"; /**< Joystick button pressed */ eventtypes[SDL_JOYBUTTONUP] = "JOYBUTTONUP"; /**< Joystick button released */ eventtypes[SDL_JOYDEVICEADDED] = "JOYDEVICEADDED"; /**< A new joystick has been inserted into the system */ eventtypes[SDL_JOYDEVICEREMOVED] = "JOYDEVICEREMOVED"; /**< An opened joystick has been removed */ /* Game controller events */ eventtypes[SDL_CONTROLLERAXISMOTION] = "CONTROLLERAXISMOTION"; /**< Game controller axis motion */ eventtypes[SDL_CONTROLLERBUTTONDOWN] = "CONTROLLERBUTTONDOWN"; /**< Game controller button pressed */ eventtypes[SDL_CONTROLLERBUTTONUP] = "CONTROLLERBUTTONUP"; /**< Game controller button released */ eventtypes[SDL_CONTROLLERDEVICEADDED] = "CONTROLLERDEVICEADDED"; /**< A new Game controller has been inserted into the system */ eventtypes[SDL_CONTROLLERDEVICEREMOVED] = "CONTROLLERDEVICEREMOVED"; /**< An opened Game controller has been removed */ eventtypes[SDL_CONTROLLERDEVICEREMAPPED] = "CONTROLLERDEVICEREMAPPED"; /**< The controller mapping was updated */ /* Touch events */ eventtypes[SDL_FINGERDOWN] = "FINGERDOWN"; eventtypes[SDL_FINGERUP] = "FINGERUP"; eventtypes[SDL_FINGERMOTION] = "FINGERMOTION"; /* Gesture events */ eventtypes[SDL_DOLLARGESTURE] = "DOLLARGESTURE"; eventtypes[SDL_DOLLARRECORD] = "DOLLARRECORD"; eventtypes[SDL_MULTIGESTURE] = "MULTIGESTURE"; /* Clipboard events */ eventtypes[SDL_CLIPBOARDUPDATE] = "CLIPBOARDUPDATE"; /**< The clipboard changed */ /* Drag and drop events */ eventtypes[SDL_DROPFILE] = "DROPFILE"; /**< The system requests a file open */ /** Events ::SDL_USEREVENT through ::SDL_LASTEVENT are for your use, * and should be allocated with SDL_RegisterEvents() */ eventtypes[SDL_USEREVENT] = "USEREVENT"; } sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Starting\n"); vid_mono_palette[0] = sim_end ? 0xFF000000 : 0x000000FF; vid_mono_palette[1] = 0xFFFFFFFF; memset (&vid_key_state, 0, sizeof(vid_key_state)); SDL_Init (SDL_INIT_VIDEO); SDL_CreateWindowAndRenderer (vid_width, vid_height, SDL_WINDOW_SHOWN, &vid_window, &vid_renderer); if ((vid_window == NULL) || (vid_renderer == NULL)) { sim_printf ("%s: Error Creating Video Window: %s\b", sim_dname(vid_dev), SDL_GetError()); SDL_Quit (); return 0; } SDL_SetRenderDrawColor (vid_renderer, 0, 0, 0, 255); SDL_RenderClear (vid_renderer); SDL_RenderPresent (vid_renderer); vid_texture = SDL_CreateTexture (vid_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, vid_width, vid_height); if (!vid_texture) { sim_printf ("%s: Error configuring Video environment: %s\b", sim_dname(vid_dev), SDL_GetError()); SDL_DestroyRenderer(vid_renderer); vid_renderer = NULL; SDL_DestroyWindow(vid_window); vid_window = NULL; SDL_Quit (); return 0; } SDL_StopTextInput (); sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Started\n"); while (vid_active) { if (SDL_WaitEvent (&event)) { switch (event.type) { case SDL_KEYDOWN: case SDL_KEYUP: vid_key ((SDL_KeyboardEvent*)&event); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: vid_mouse_button ((SDL_MouseButtonEvent*)&event); break; case SDL_MOUSEMOTION: vid_mouse_move ((SDL_MouseMotionEvent*)&event); break; case SDL_USEREVENT: /* There are 2 user events generated */ /* EVENT_REDRAW to update the display */ /* EVENT_CLOSE to wake up this thread and let */ /* it notice vid_active has changed */ if (event.user.code == EVENT_REDRAW) vid_update (); break; default: sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Ignored Event: Type: %s(%d)\n", eventtypes[event.type], event.type); break; } } } SDL_DestroyTexture(vid_texture); vid_texture = NULL; SDL_DestroyRenderer(vid_renderer); vid_renderer = NULL; SDL_DestroyWindow(vid_window); vid_window = NULL; SDL_Quit (); sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Exiting\n"); return 0; }
int LancerJeu(gpointer *pData) { /* Cette fonction va appeler les fonctions d'initialisations de la SDL et lancer le jeu ou l'éditeur */ SDL_Renderer *pMoteurRendu = NULL; //Pointeurs sur le moteur de rendu SDL_Window *pFenetre = NULL; //Pointeur sur la fenêtre FMOD_CHANNEL *channelEnCours = NULL; //Pour le contrôle des différents canaux audios Sprite images[50] = {{NULL}, {0,0}}; //Tableau des images (textures + positions) TTF_Font *polices[10] = {NULL}; //Tableau des polices Options *pOptions = NULL; //Pointeur sur une structure Options FILE *pFichierErreur = fopen("ressources/ErreursLog.txt", "a"); //Pointeur sur le fichier d'erreurs SDL_Surface *surf = NULL; //Pointeur sur une surface SDL_Texture *pEcranChargement = NULL; //Pointeur sur une texture pour l'écran de chargement Animation anim[10]; //Tableau de structures Animation int erreur=0; //Code d'erreur Joueur *pJoueur = (Joueur *)g_slist_nth_data((GSList*)pData, 6); //On récupère le pointeur vers la structure Joueur dans la liste chaînée Sons *pSons = (Sons*)g_slist_nth_data((GSList*)pData, 4); //De même avec celui vers la structure Sons FMOD_SYSTEM *pMoteurSon = (FMOD_SYSTEM *)g_slist_nth_data((GSList*)pData, 3); //De même avec celui vers la structure FMOD_SYSTEM if(pFichierErreur == NULL) //Vérification { exit(EXIT_FAILURE); } /* On lit les options et on remplit la structure */ pOptions = DefinirOptions(); Initialisation(&pMoteurRendu, pFichierErreur, &pFenetre, pOptions); //Initialisation des principaux éléments (SDL, fenêtre, moteur de rendu) FMOD_System_GetChannel(pMoteurSon, M_MENU, &channelEnCours); //On met en pause la musique du menu FMOD_Channel_SetPaused(channelEnCours, true); if(BMusique) //S'il y a de la musique { FMOD_System_PlaySound(pMoteurSon, M_LOAD, pSons->music[M_LOAD], true, NULL); // On lit la musique de chargement FMOD_System_GetChannel(pMoteurSon, M_LOAD, &channelEnCours); FMOD_Channel_SetVolume(channelEnCours, (float)(Volume/100.0)); FMOD_Channel_SetPaused(channelEnCours, false); } /* On charge l'image de chargement et on vérifie */ surf = IMG_Load("ressources/img/load.png"); if (surf == NULL) { fprintf(pFichierErreur, "Erreur: impossible d'ouvrir le fichier ressources/img/load.png"); exit(EXIT_FAILURE); } /* On transforme la surface en texture pour l'affichage et on libère la mémoire occupée par la surface */ pEcranChargement = SDL_CreateTextureFromSurface(pMoteurRendu, surf); SDL_FreeSurface(surf); SDL_ShowCursor(false); //On masque le curseur pendant le jeu (on affichera un curseur personnalisé dans l'éditeur) /* On efface l'écran et on colle l'image de chargement */ SDL_SetRenderDrawColor(pMoteurRendu, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(pMoteurRendu); SDL_RenderCopy(pMoteurRendu, pEcranChargement, NULL, NULL); SDL_RenderPresent(pMoteurRendu); SDL_EventState(SDL_TEXTEDITING, SDL_DISABLE); //Désactivation des événements dont on a pas besoin. SDL_EventState(SDL_TEXTINPUT, SDL_DISABLE); SDL_DisableScreenSaver(); //Désactivation de l'écran de veille. erreur = Chargements(images, pMoteurRendu, polices, anim); //On charge tout ! /* Traitement des éventuelles erreurs */ if(erreur == 1) { fprintf(pFichierErreur, "Erreur lors du chargement des images. Veuillez vérifier ressources\\img\\... \n"); exit(EXIT_FAILURE); } else if (erreur == 2) { fprintf(pFichierErreur, "Erreur lors du chargement des polices. Veuillez vérifier ressources\\fonts\\... \n"); exit(EXIT_FAILURE); } else if (erreur == 3) { fprintf(pFichierErreur, "Erreur lors du chargement des animations. Veuillez vérifier ressources\\anim\\... \n"); exit(EXIT_FAILURE); } if (BMusique) { FMOD_System_GetChannel(pMoteurSon, M_LOAD, &channelEnCours); //On arrête la musique du chargement FMOD_Channel_SetPaused(channelEnCours, true); FMOD_Sound_SetLoopCount(pSons->music[M_JEU], -1); // On active la lecture en boucle FMOD_System_PlaySound(pMoteurSon, M_JEU, pSons->music[M_JEU], true, NULL); // On lit la musique du jeu FMOD_System_GetChannel(pMoteurSon, M_JEU, &channelEnCours); FMOD_Channel_SetVolume(channelEnCours, (float)(Volume/100.0)); FMOD_Channel_SetPaused(channelEnCours, false); } /* On regarde si on a appelé la fonction en mode jeu ou en mode éditeur */ if (pJoueur->mode == MODE_CAMPAGNE) { InitialiserInfos(pOptions, pJoueur); //On définit les infos sur la partie en cours erreur = BouclePrincipale(pJoueur, images, anim, pMoteurRendu, pMoteurSon, pSons, polices); //Boucle du jeu if(erreur == JEU_FIN_ERREUR_CHARGEMENT) { MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL); } SauverMySql(pJoueur); //On sauvegarde l'avancée du joueur } else if(pJoueur->mode == MODE_PERSO) { InitialiserInfos(pOptions, pJoueur); //On définit les infos sur la partie en cours erreur = BouclePrincipale(pJoueur, images, anim, pMoteurRendu, pMoteurSon, pSons, polices); //Boucle du jeu if(erreur == JEU_FIN_ERREUR_CHARGEMENT) { MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL); } } else if (pJoueur->mode == MODE_EDITEUR) { erreur = Editeur(pMoteurRendu, images, pMoteurSon, pSons, polices, pJoueur); //On lance la boucle de l'éditeur if(erreur == JEU_FIN_ERREUR_CHARGEMENT) { MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL); } } /* Libération de la mémoire */ LibererMemoire(pMoteurRendu, images, anim, polices, pFenetre, pOptions); fclose(pFichierErreur); //On ferme le fichier d'erreur return 0; }
void gfxengine_t::flip() { if(!screen_surface) return; // Init dirtyrect table flipping, if necessary. switch(_pages) { case -1: if(!_doublebuf) frontpage = backpage = 0; else if(frontpage == backpage) { frontpage = 0; backpage = 1; } break; case 0: frontpage = backpage = 0; invalidate(); break; case 1: frontpage = backpage = 0; break; case 2: case 3: if(frontpage == backpage) { frontpage = 0; backpage = 1; } break; } // Process the dirtyrects. int i; for(i = 0; i < dirtyrects[backpage]; ++i) { if(dirtywtable[backpage][i]) { if(!dirtywtable[backpage][i]->visible()) continue; SDL_Rect dr = dirtytable[backpage][i]; dirtywtable[backpage][i]->phys_refresh(&dr); } else refresh_rect(&dirtytable[backpage][i]); } // Perform the actual flip or update if(_shadow) { for(i = 0; i < dirtyrects[backpage]; ++i) SDL_BlitSurface(softbuf, &dirtytable[backpage][i], screen_surface, &dirtytable[backpage][i]); } if(_doublebuf) { dirtyrects[backpage] = 0; if(_pages == -1) { backpage = !backpage; frontpage = !frontpage; } else if(_pages > 1) { backpage = (backpage + 1) % _pages; frontpage = (frontpage + 1) % _pages; } SDL_UpdateTexture(sdlTexture, NULL, screen_surface->pixels, screen_surface->pitch); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, sdlTexture, NULL, NULL); SDL_RenderPresent(renderer); // SDL_UpdateWindowSurface(myscreen); // SDL_Flip(screen_surface); // SDL_RenderPresent(SDL_CreateSoftwareRenderer(screen_surface)); } else { SDL_UpdateTexture(sdlTexture, NULL, screen_surface->pixels, screen_surface->pitch); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, sdlTexture, NULL, NULL); SDL_RenderPresent(renderer); // SDL_UpdateWindowSurface(myscreen); // SDL_UpdateRects(screen_surface, dirtyrects[0], dirtytable[0]); // SDL_RenderPresent(SDL_CreateSoftwareRenderer(screen_surface)); dirtyrects[0] = 0; } }
void SDLApp::OnFrame(float dt) { SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255); SDL_RenderClear(renderer_); SDL_RenderPresent(renderer_); }
void CSDL_setup::end() { SDL_RenderPresent(renderer); }
/* In order to avoid rendering race conditions and the ensuing segmentation * faults, this should only be called when it would normally be and not * specifically to force screen refreshes. To this end, and to avoid * threading complications it takes care of special cases internally. */ static void render(void *vbitmap, int console_width, int console_height, char_t *console_buffer, char_t *prev_console_buffer) { char_t *prev_console_buffer_ptr = prev_console_buffer; if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { int console_width_p = console_width*TCOD_ctx.font_width; int console_height_p = console_height*TCOD_ctx.font_height; /* Make a bitmap of exact rendering size and correct format. */ if (scale_screen == NULL) { int bpp; Uint32 rmask, gmask, bmask, amask; if (SDL_PixelFormatEnumToMasks(SDL_GetWindowPixelFormat(window), &bpp, &rmask, &gmask, &bmask, &amask) == SDL_FALSE) { TCOD_fatal("SDL : failed to create scaling surface : indeterminate window pixel format"); return; } scale_screen=SDL_CreateRGBSurface(SDL_SWSURFACE,console_width_p,console_height_p,bpp,rmask,gmask,bmask,amask); if (scale_screen == NULL) { TCOD_fatal("SDL : failed to create scaling surface"); return; } } else if (clear_screen) { clear_screen=false; SDL_FillRect(scale_screen,0,0); /* Implicitly do complete console redraw, not just tracked changes. */ prev_console_buffer_ptr = NULL; } TCOD_sys_console_to_bitmap(scale_screen, console_width, console_height, console_buffer, prev_console_buffer_ptr); /* Scale the rendered bitmap to the screen, preserving aspect ratio, and blit it. * This data is also used for console coordinate resolution.. */ if (scale_data.last_scale_factor != scale_factor || scale_data.last_scale_xc != scale_xc || scale_data.last_scale_yc != scale_yc || scale_data.last_fullscreen != TCOD_ctx.fullscreen || scale_data.force_recalc) { /* Preserve old value of input variables, to enable recalculation if they change. */ scale_data.last_scale_factor = scale_factor; scale_data.last_scale_xc = scale_xc; scale_data.last_scale_yc = scale_yc; scale_data.last_fullscreen = TCOD_ctx.fullscreen; scale_data.force_recalc = 0; if (scale_data.last_fullscreen) { scale_data.surface_width = TCOD_ctx.actual_fullscreen_width; scale_data.surface_height = TCOD_ctx.actual_fullscreen_height; } else { scale_data.surface_width = console_width_p; scale_data.surface_height = console_height_p; } scale_data.min_scale_factor = MAX((float)console_width_p/scale_data.surface_width, (float)console_height_p/scale_data.surface_height); if (scale_data.min_scale_factor > 1.0f) scale_data.min_scale_factor = 1.0f; /*printf("min_scale_factor %0.3f = MAX(%d/%d, %d/%d)", scale_data.min_scale_factor, console_width_p, scale_data.surface_width, console_height_p, scale_data.surface_height);*/ scale_data.dst_height_width_ratio = (float)scale_data.surface_height/scale_data.surface_width; scale_data.src_proportionate_width = (int)(console_width_p / scale_factor); scale_data.src_proportionate_height = (int)((console_width_p * scale_data.dst_height_width_ratio) / scale_factor); /* Work out how much of the console to copy. */ scale_data.src_x0 = (scale_xc * console_width_p) - (0.5f * scale_data.src_proportionate_width); if (scale_data.src_x0 + scale_data.src_proportionate_width > console_width_p) scale_data.src_x0 = console_width_p - scale_data.src_proportionate_width; if (scale_data.src_x0 < 0) scale_data.src_x0 = 0; scale_data.src_copy_width = scale_data.src_proportionate_width; if (scale_data.src_x0 + scale_data.src_copy_width > console_width_p) scale_data.src_copy_width = console_width_p - scale_data.src_x0; scale_data.src_y0 = (scale_yc * console_height_p) - (0.5f * scale_data.src_proportionate_height); if (scale_data.src_y0 + scale_data.src_proportionate_height > console_height_p) scale_data.src_y0 = console_height_p - scale_data.src_proportionate_height; if (scale_data.src_y0 < 0) scale_data.src_y0 = 0; scale_data.src_copy_height = scale_data.src_proportionate_height; if (scale_data.src_y0 + scale_data.src_copy_height > console_height_p) scale_data.src_copy_height = console_height_p - scale_data.src_y0; scale_data.dst_display_width = (scale_data.src_copy_width * scale_data.surface_width) / scale_data.src_proportionate_width; scale_data.dst_display_height = (scale_data.src_copy_height * scale_data.surface_height) / scale_data.src_proportionate_height; scale_data.dst_offset_x = (scale_data.surface_width - scale_data.dst_display_width)/2; scale_data.dst_offset_y = (scale_data.surface_height - scale_data.dst_display_height)/2; } SDL_RenderClear(renderer); actual_rendering(); SDL_RenderPresent(renderer); } #ifndef NO_OPENGL else { TCOD_opengl_render(oldFade, ascii_updated, console_buffer, prev_console_buffer); TCOD_opengl_swap(); } #endif oldFade=(int)TCOD_console_get_fade(); if ( any_ascii_updated ) { memset(ascii_updated,0,sizeof(bool)*TCOD_ctx.max_font_chars); any_ascii_updated=false; } }
void CSDL_Setup::End() { SDL_RenderPresent(renderer); }
void loop() { int i; SDL_Event event; /* Check for events */ while (SDL_PollEvent(&event)) { SDLTest_CommonEvent(state, &event, &done); if (event.type == SDL_WINDOWEVENT) { if (event.window.event == SDL_WINDOWEVENT_RESIZED) { SDL_Window *window = SDL_GetWindowFromID(event.window.windowID); if (window) { SDL_Log("Window %d resized to %dx%d\n", event.window.windowID, event.window.data1, event.window.data2); } } if (event.window.event == SDL_WINDOWEVENT_MOVED) { SDL_Window *window = SDL_GetWindowFromID(event.window.windowID); if (window) { SDL_Log("Window %d moved to %d,%d (display %s)\n", event.window.windowID, event.window.data1, event.window.data2, SDL_GetDisplayName(SDL_GetWindowDisplayIndex(window))); } } } if (event.type == SDL_KEYUP) { SDL_bool updateCursor = SDL_FALSE; if (event.key.keysym.sym == SDLK_LEFT) { --system_cursor; if (system_cursor < 0) { system_cursor = SDL_NUM_SYSTEM_CURSORS - 1; } updateCursor = SDL_TRUE; } else if (event.key.keysym.sym == SDLK_RIGHT) { ++system_cursor; if (system_cursor >= SDL_NUM_SYSTEM_CURSORS) { system_cursor = 0; } updateCursor = SDL_TRUE; } if (updateCursor) { SDL_Log("Changing cursor to \"%s\"", cursorNames[system_cursor]); SDL_FreeCursor(cursor); cursor = SDL_CreateSystemCursor((SDL_SystemCursor)system_cursor); SDL_SetCursor(cursor); } } } for (i = 0; i < state->num_windows; ++i) { SDL_Renderer *renderer = state->renderers[i]; SDL_RenderClear(renderer); SDL_RenderPresent(renderer); } #ifdef __EMSCRIPTEN__ if (done) { emscripten_cancel_main_loop(); } #endif }
void ViewerSdl::EndDraw() { SDL_RenderPresent(this->renderer); }
int main(int argc, char** argv) { SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("SDL Practice4", SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, 800,700, SDL_WINDOW_SHOWN); SDL_Renderer* rend = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); //创建renderer SDL_RenderClear(rend); //清空rend SDL_Surface* image_surface = SDL_LoadBMP("x.bmp"); SDL_Texture* image_texture = SDL_CreateTextureFromSurface(rend, image_surface); //将surface转换为texture并显示在rend上 SDL_Event event; SDL_Rect pos; pos.x=0; pos.y=0; pos.w=image_surface->w; pos.h=image_surface->h; SDL_Rect image_pos; image_pos.x = 0; image_pos.y = 0; image_pos.w = image_surface->w; image_pos.h = image_surface->h; bool quit=false; bool pressed = false; while(!quit) { while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) quit = true; if(event.type == SDL_MOUSEBUTTONDOWN) { if(event.button.button == SDL_BUTTON_LEFT) { image_pos.x = event.motion.x - pos.x; image_pos.y = event.motion.y - pos.y; if(image_pos.x>=0 && image_pos.x<=image_pos.w && image_pos.y>0 && image_pos.y<image_pos.h) pressed = true; } } if(pressed && event.type == SDL_MOUSEMOTION) { pos.x = event.motion.x - image_pos.x; pos.y = event.motion.y - image_pos.y; } if(event.type == SDL_MOUSEBUTTONUP) { if(pressed && event.button.button == SDL_BUTTON_LEFT) { pressed = false; } } } SDL_RenderClear(rend); //清空rend SDL_RenderCopy(rend, image_texture, NULL, &pos); //将texture显示到rend上 SDL_Delay(5); SDL_RenderPresent(rend); //显示rend } SDL_DestroyWindow(window); SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { // initialize SDL if (SDL_Init(SDL_INIT_VIDEO)) { printf("SDL_Init: %s\n", SDL_GetError()); return -1; } // create the window SDL_Window *window = SDL_CreateWindow( "Template", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); if (!window) { printf("SDL_CreateWindow: %s\n", SDL_GetError()); return -1; } // create a renderer for the window SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { printf("SDL_CreateRenderer: %s\n", SDL_GetError()); return -1; } // load the mario image SDL_Surface *marioSurface = SDL_LoadBMP("mario.bmp"); if (!marioSurface) { printf("SDL_LoadBMP: %s\n", SDL_GetError()); return -1; } // create a duplicate of the mario surface with the same pixel format as the window SDL_Surface *newMarioSurface = SDL_ConvertSurfaceFormat(marioSurface, SDL_GetWindowPixelFormat(window), 0); // no longer need to hang on to the original image SDL_FreeSurface(marioSurface); // set (255,0,255) as the transparent color if (SDL_SetColorKey(newMarioSurface, SDL_TRUE, SDL_MapRGB(newMarioSurface->format, 255, 0, 255))) { printf("SDL_SetColorKey: %s\n", SDL_GetError()); return -1; } // create a renderable texture from the image SDL_Texture *marioTexture = SDL_CreateTextureFromSurface(renderer, newMarioSurface); if (!marioTexture) { printf("SDL_CreateTextureFromSurface: %s\n", SDL_GetError()); return -1; } // no longer need to hang on to the converted image SDL_FreeSurface(newMarioSurface); typedef enum MarioState { MARIO_JUMPING, MARIO_WALKING, MARIO_IDLE } MarioState; // current state of mario MarioState marioState = MARIO_IDLE; // position of mario in the world float marioXPosition = 200; float marioYPosition = 200; float marioMovementSpeed = 50; // pixels per second // stores whether or not the mario state should be flipped SDL_RendererFlip marioFlipping = SDL_FLIP_NONE; // will use the time between state switches to know what frame of animation to use Uint32 timeOfLastStateSwitch = SDL_GetTicks(); Uint32 timeOfLastFrame = SDL_GetTicks(); // begin main loop int isGameRunning = 1; while (isGameRunning) { // count the number of milliseconds since the last frame Uint32 timeOfThisFrame = SDL_GetTicks(); Uint32 frameDeltaTime = timeOfThisFrame - timeOfLastFrame; timeOfLastFrame = timeOfThisFrame; // handle all the events SDL_Event e; while (SDL_PollEvent(&e)) { // if the window is being requested to close, then stop the game. if (e.type == SDL_QUIT) { isGameRunning = 0; } } // store the old state to know if the state has changed MarioState oldMarioState = marioState; // get a lookup table to know if keys are pressed const Uint8 *keyboardState = SDL_GetKeyboardState(NULL); // handle left movement key if (keyboardState[SDL_SCANCODE_LEFT]) { marioXPosition -= marioMovementSpeed * (frameDeltaTime / 1000.0f); marioFlipping = SDL_FLIP_NONE; // switch to walking state marioState = MARIO_WALKING; } // handle right movement key if (keyboardState[SDL_SCANCODE_RIGHT]) { marioXPosition += marioMovementSpeed * (frameDeltaTime / 1000.0f); marioFlipping = SDL_FLIP_HORIZONTAL; // switch to walking state marioState = MARIO_WALKING; } // if nothing's being pressed, then we're in the idle state if (!keyboardState[SDL_SCANCODE_LEFT] && !keyboardState[SDL_SCANCODE_RIGHT]) { marioState = MARIO_IDLE; } // update the time of the last state switch if (marioState != oldMarioState) { timeOfLastStateSwitch = SDL_GetTicks(); } // render everything if (SDL_RenderClear(renderer)) { printf("SDL_RenderClear: %s\n", SDL_GetError()); return -1; } // decide frame of animation to use int currentSpriteFrame; if (marioState == MARIO_IDLE) { currentSpriteFrame = 2; } else if (marioState == MARIO_WALKING) { // get the index of the frame we're currently at (12 fps animation speed) Uint32 millisecondsPerFrame = 1000/12; Uint32 framesPassedSinceStateSwitch = (SDL_GetTicks() - timeOfLastStateSwitch) / millisecondsPerFrame; // if we're on an odd frame, use the standing animation. // if we're on an even frame, use the walking animation. if (framesPassedSinceStateSwitch & 1) { currentSpriteFrame = 2; } else { currentSpriteFrame = 1; } } else { currentSpriteFrame = 0; } // set up the rendering for mario // note: each frame in the animation has size 16x32 in the sprite sheet // the source rectangle defines which region of the sprite sheet to use SDL_Rect renderSourceRect; renderSourceRect.x = currentSpriteFrame * 16; renderSourceRect.y = 0; renderSourceRect.w = 16; renderSourceRect.h = 32; // the destination rectangle defines which region of the screen to draw it to SDL_Rect renderDestinationRect; renderDestinationRect.x = marioXPosition; renderDestinationRect.y = marioYPosition - 32 * 2; // sprite is scaled 2x renderDestinationRect.w = 16 * 2; // sprite is scaled 2x renderDestinationRect.h = 32 * 2; // sprite is scaled 2x // finally, do the real rendering if (SDL_RenderCopyEx( renderer, marioTexture, &renderSourceRect, &renderDestinationRect, 0.0, // no rotation NULL, // no center of rotation marioFlipping)) { printf("SDL_RenderCopy: %s\n", SDL_GetError()); return -1; } // flip the display SDL_RenderPresent(renderer); // throttle the frame rate to 60fps SDL_Delay(1000/60); } // throw everything away SDL_Quit(); return 0; }
int main(void) { // int good = 0; // int numeroMap = 0; // do{ // printf("Quelle map?\n"); // printf("1 - Original\n"); // printf("2 - Hard\n"); // printf("3 - Lol\n"); // printf("4 - Rez De chaussez Aile Sud Telecom Nancy\n"); // scanf("%d", &numeroMap); // switch(numeroMap){ // case 1: // loadMap("../projec/map/original.map"); // good = 1; // break; // case 2: // loadMap("../projec/map/hard.map"); // good = 1; // break; // case 3: // loadMap("../projec/map/maplol.map"); // good = 1; // break; // case 4: // loadMap("../projec/map/rdastn.map"); // good = 1; // break; // case 42: // loadMap("../projec/map/rdastn.map"); // good = 1; // setQ(); // break; // } // }while(!good); //Create SDL objects SDL_Window *window = 0; SDL_Event event; SDL_Renderer *renderer = 0; int terminate = 0; //Initialise SDL if(SDL_Init(SDL_INIT_VIDEO) < 0){ printf("Error with SDL : %s\n", SDL_GetError()); SDL_Quit(); return EXIT_FAILURE; } window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 544, 344, SDL_WINDOW_SHOWN); terminate = 0; renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_Surface *menu = IMG_Load("../projec/texture/menu/menu.jpg"); SDL_Texture *menuTexture = SDL_CreateTextureFromSurface(renderer, menu); SDL_FreeSurface(menu); SDL_RenderClear(renderer); int x, y; while(!terminate){ SDL_Rect dest = {0, 0, 544, 344}; SDL_RenderCopy(renderer, menuTexture, NULL, &dest); SDL_RenderPresent(renderer); SDL_WaitEvent(&event); switch(event.type){ case SDL_MOUSEBUTTONDOWN: x = event.motion.x; y = event.motion.y; if(x >= 57 && x <= (57+54) && y >= 94 && y <= (94 + 74)){ loadMap("../projec/map/original.map"); terminate = 1; } if(x >= 124 && x <= (124+53) && y >= 208 && y <= (208 + 73)){ loadMap("../projec/map/hard.map"); terminate = 1; } if(x >= 221 && x <= (221+59) && y >= 95 && y <= (95 + 80)){ loadMap("../projec/map/maplol.map"); terminate = 1; } if(x >= 311 && x <= (311+63) && y >= 208 && y <= (208 + 76)){ loadMap("../projec/map/rdastn.map"); terminate = 1; } if(x >= 350 && x <= (350+124) && y >= 73 && y <= (73 + 109)){ loadMap("../projec/map/rdastn.map"); terminate = 1; setQ(); } break; } SDL_Delay(1000 / FPS); } SDL_DestroyTexture(menuTexture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); //Search the pacman on the map and create him Pacman *pacman = getPacmanInstance(); unsigned int initialX = pacman->x; unsigned int initialY = pacman->y; Map *map = getMapInstance(); //If the pacman is not found if(!pacman){ printf("Pacman not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Pacman found !\n"); Ghost *clyde = searchAndCreateGhost(CLYDE); if(!clyde){ printf("Clyde not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Clyde found !\n"); Ghost *blinky = searchAndCreateGhost(BLINKY); if(!blinky){ printf("Blinky not found on map\n"); freeMap(map); freeGhost(clyde); exit(EXIT_FAILURE); } printf("Blinky found !\n"); Ghost *inky = searchAndCreateGhost(INKY); if(!inky){ printf("Inky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); exit(EXIT_FAILURE); } printf("Inky found !\n"); Ghost *pinky = searchAndCreateGhost(PINKY); if(!pinky){ printf("Pinky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); exit(EXIT_FAILURE); } printf("Pinky found !\n"); printf("SDL initialisation\n"); if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1){ printf("%s", Mix_GetError()); } Mix_Music *music = NULL; music = Mix_LoadMUS("../projec/pacman.wav"); if(!music){ printf("Erreur de chargement de la musique %s \n", Mix_GetError()); }else{ Mix_VolumeMusic(MIX_MAX_VOLUME); Mix_PlayMusic(music, -1); } if(TTF_Init() == -1){ printf("Error during TTF initialization : %s\n", TTF_GetError()); } TTF_Font *police = NULL; police = TTF_OpenFont("../projec/monof.ttf", 65); if(!police){ printf("Error during font load : %s\n", TTF_GetError()); } SDL_Color color = { 255, 255, 255, 255}; //Create the window window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TILE_SIZE * map->col, TILE_SIZE * map->row + TILE_SIZE, SDL_WINDOW_SHOWN); //If there is an error if(window == 0){ printf("Error during window creation : %s \n", SDL_GetError()); SDL_Quit(); freeMap(map); return EXIT_FAILURE; } int j; printf("SDL init success\n"); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); //NEED gerer erreurs loadTextures(renderer); SDL_Surface *score = TTF_RenderText_Solid(police, "Score : ", color); SDL_Texture *scoreT = SDL_CreateTextureFromSurface(renderer, score); SDL_FreeSurface(score); char scoreString[15]; SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_Surface *scoreN; SDL_Texture *scoreTN; int open = 0; int konami[10] = {0,0,0,0,0,0,0,0,0,0}; //Infinite loop until we want to stop the game terminate = 0; while(!terminate){ SDL_Rect dest2 = {map->row * TILE_SIZE / 6, map->row * TILE_SIZE, map->row * TILE_SIZE / 15, 20}; sprintf(scoreString, "%d", pacman->point); scoreN = TTF_RenderText_Solid(police, scoreString, color); scoreTN = SDL_CreateTextureFromSurface(renderer, score); renderMap(renderer); open = renderPacman(open, renderer); renderClyde(clyde, renderer); renderBlinky(blinky, renderer); renderPinky(pinky, renderer); renderInky(inky, renderer); changeDirectionGhost(blinky); changeDirectionGhost(clyde); changeDirectionGhost(inky); changeDirectionGhost(pinky); SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_RenderCopy(renderer, scoreTN, NULL, &dest2); SDL_RenderPresent(renderer); //Event handling SDL_PollEvent(&event); switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.scancode){ case SDL_SCANCODE_UP: setPacmanDirection(NORTH); if(konami[0]){ if(konami[1]){ for(j = 0 ; j < 10 ; j++){ konami[j] = 0; } // printf("Déjà deux\n"); }else{ konami[1] = 1; } }else{ konami[0] = 1; } break; case SDL_SCANCODE_DOWN: setPacmanDirection(SOUTH); break; case SDL_SCANCODE_RIGHT: setPacmanDirection(EAST); break; case SDL_SCANCODE_LEFT: setPacmanDirection(WEST); break; default: break; } break; } terminate = update(clyde, blinky, inky, pinky); if(terminate){ if(pacman->life > 0 ){ pacman->life--; terminate = 0; pacman->x = initialX; pacman->y = initialY; } } if(event.window.event == SDL_WINDOWEVENT_CLOSE){ terminate = 1; } SDL_Delay(1000 / FPS); SDL_DestroyTexture(scoreTN); SDL_FreeSurface(scoreN); } printf("Score final : %d\n", pacman->point); Mix_FreeMusic(music); Mix_CloseAudio(); freeTextures(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); SDL_DestroyTexture(scoreT); freePacman(); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); freeGhost(pinky); freeMap(); TTF_CloseFont(police); TTF_Quit(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { if(argc < 2) return 1; char dvd_filename[MAX_PATH]; char dvm_filename[MAX_PATH]; snprintf(dvd_filename, MAX_PATH-1, "%s.dvd", argv[1]); snprintf(dvm_filename, MAX_PATH-1, "%s.dvm", argv[1]); int err = 0; struct dvd_file *file = dvd_file_open(dvd_filename, &err); if (!file) { fprintf(stderr, "dvd_file_open failed\n"); return -1; } union dvd_entry entry; while (dvd_file_has_next(file)) { if ((err = dvd_file_get_next(file, &entry))) { fprintf(stderr, "dvd_file_get_next failed\n"); return -2; } switch (entry.type) { case DVD_ENTRY_TYPE_MISC: printf("misc entry: size %d\n", entry.misc.size); break; case DVD_ENTRY_TYPE_UNKN: default: break; } dvd_entry_done(&entry); } dvd_file_close(file); return 0; unsigned int width, height; void *pixmap = dvm_file_get_pixmap(dvm_filename, &width, &height, NULL); if (!pixmap) { fprintf(stderr, "failed getting pixmap\n"); return -1; } SDL_Init(SDL_INIT_VIDEO); SDL_Window *w = SDL_CreateWindow("DVF tool", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, -1, -1, SDL_WINDOW_FULLSCREEN_DESKTOP); SDL_Renderer *renderer = SDL_CreateRenderer(w, -1, SDL_RENDERER_ACCELERATED); SDL_Surface *surface = SDL_CreateRGBSurface(0, width, height, 16, 0, 0, 0, 0); surface->pixels = pixmap; SDL_Texture *tex = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = width; rect.h = height; int move = 0, mouse_x, mouse_y, diff_x = 0, diff_y = 0; int offset_x, offset_y; SDL_Event event; while (1) { while(SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { goto exit; } switch (event.type) { case SDL_MOUSEBUTTONDOWN: move = 1; mouse_x = event.button.x; mouse_y = event.button.y; break; case SDL_MOUSEBUTTONUP: move = 0; diff_x = 0; diff_y = 0; break; case SDL_MOUSEMOTION: if (move) { rect.x -= diff_x; rect.y -= diff_y; diff_x = event.motion.x - mouse_x; diff_y = event.motion.y - mouse_y; rect.x += diff_x; rect.y += diff_y; } break; } } SDL_RenderClear(renderer); SDL_RenderCopy(renderer, tex, NULL, &rect); SDL_RenderPresent(renderer); SDL_Delay(10); } exit: SDL_DestroyTexture(tex); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(w); SDL_Quit(); return 0; }
void screen_update(Screen* s, CPU* c) { int i; int mem = 0; SDL_Rect fr; fr.w = char_w; fr.h = char_h; SDL_Rect sr; sr.x = 0; sr.y = 0; sr.w = char_w; sr.h = char_h; SDL_SetRenderDrawColor(s->renderer, 0, 0, 0, 0); SDL_RenderClear(s->renderer); int x = 0; int y = 0; for(i = 0; i < 80*30; i++) { u8 ch = c->mem[VIDEO_START+(mem++)]; u8 col = c->mem[VIDEO_START+(mem++)]; if(col == 0) { x++; if(x >= 80) { x = 0; y++; } continue; } u8 ch_x = (ch % font_w) * char_w; u8 ch_y = (ch / font_h) * char_h; fr.x = ch_x; fr.y = ch_y; sr.x = x * char_w; sr.y = y * char_h; u8 bg = (col & 0xF0) >> 4; if(bg != 0) { SDL_SetRenderDrawColor(s->renderer, colors[bg].r, colors[bg].g, colors[bg].b, 255); SDL_RenderFillRect(s->renderer, &sr); } u8 fg = (col & 0xF); SDL_SetTextureColorMod(s->font, colors[fg].r, colors[fg].g, colors[fg].b); SDL_RenderCopy(s->renderer, s->font, &fr, &sr); x++; if(x >= 80) { x = 0; y++; } } u8 fg = c->mem[SCREEN_COLOR] & 0x0F; if(c->mem[SCREEN_BLINK_INTERVAL] == 0){ }else if(c->mem[SCREEN_BLINK_INTERVAL] == 1) { SDL_SetRenderDrawColor(s->renderer, colors[fg].r, colors[fg].g, colors[fg].b, 255); SDL_RenderFillRect(s->renderer,&(SDL_Rect){c->mem[SCREEN_CURSOR_X]*char_w, c->mem[SCREEN_CURSOR_Y]*char_h+(char_h-2), char_w, 2}); }else if(blinky >= c->mem[SCREEN_BLINK_INTERVAL]) { blinky++; if(blinky >= c->mem[SCREEN_BLINK_INTERVAL]*2) blinky = 0; }else { SDL_SetRenderDrawColor(s->renderer, colors[fg].r, colors[fg].g, colors[fg].b, 255); SDL_RenderFillRect(s->renderer,&(SDL_Rect){c->mem[SCREEN_CURSOR_X]*char_w, c->mem[SCREEN_CURSOR_Y]*char_h+(char_h-2), char_w, 2}); blinky++; } SDL_RenderPresent(s->renderer); }
int main(int argc, char **argv){ SDL_Window *window = 0; SDL_Renderer *renderer = 0; SDL_Texture *texture = 0; SDL_Event event; bool run = true; mouse mymouse; timer timer(60); unit myunit(300,300); if(SDL_Init(SDL_INIT_EVERYTHING) != 0 ){ std::cout<< "SDL init error: " << SDL_GetError() << std::endl; return 1; } if(SDL_CreateWindowAndRenderer(KSCREEN_WIDTH,KSCREEN_HEIGHT,0,&window,&renderer) !=0 ){ std::cout<< "Create window and renderer error: " << SDL_GetError() << std::endl; return 1; } texture = util_create_texture_from_bitmap("background.bmp",renderer); while(run){ timer.start(); while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_QUIT: run = false; break; case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_ESCAPE: run = false; break; case SDLK_DOWN: printf("left pressed\n"); break; } break; } } myunit.run(renderer,&event,mymouse); //doesnt flicker when here mymouse.run(renderer,&event); //SDL_RenderDrawLine(renderer,0,0,640,480); // test line.. SDL_RenderPresent(renderer); util_render_texture_to_renderer(0,0,texture,renderer); //using background as a clear.. timer.end(); timer.delay(); } SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); std::cout<<"quit success" << std::endl; return 0; }
void NextFrame() { SDL_RenderPresent(renderer); FrameDelay(); }
void Init_2DGraphics( Dict *config ) { int flags = 0; int tmp = 0; if( !config ) { Log( FATAL, "No config to initialize graphics system" ); exit( -1 ); } Log( INFO, "Initializing Graphics" ); Vec2_Clear( _resolution ); Vec2_Clear( _render_resolution ); Vec4_Clear( _background_color_v ); /* set config stuff */ Str_As_Vec2( Find_In_Dict( config, "resolution" ), _resolution ); Str_As_Vec2( Find_In_Dict( config, "render_resolution" ), _render_resolution ); Str_As_UInt( Find_In_Dict( config, "bpp" ), &_bpp ); Str_As_UInt( Find_In_Dict( config, "frame_delay" ), &_frame_delay ); Str_As_Vec4( Find_In_Dict( config, "background_color" ), _background_color_v ); Str_As_Int( Find_In_Dict( config, "fullscreen" ), &tmp ); if( tmp ) flags |= SDL_WINDOW_FULLSCREEN; Str_As_Int( Find_In_Dict( config, "borderless" ), &tmp ); if( tmp ) flags |= SDL_WINDOW_BORDERLESS; /* set up the graphics */ _main_window = SDL_CreateWindow( "Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, _resolution[ 0 ], _resolution[ 1 ], flags ); if( !_main_window ) { Log( FATAL, "Failed to Create the Main Window" ); exit( -1 ); } _renderer = SDL_CreateRenderer( _main_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE ); if( !_renderer ) { Log( FATAL, "Failed to Create the Renderer" ); exit( -1 ); } SDL_SetRenderDrawColor( _renderer, 0, 0, 0, 255 ); SDL_RenderClear( _renderer ); SDL_RenderPresent( _renderer ); SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "linear" ); SDL_RenderSetLogicalSize( _renderer, _render_resolution[ 0 ], _render_resolution[ 1 ] ); SDL_PixelFormatEnumToMasks( SDL_PIXELFORMAT_RGBA8888, ( int* )&_bpp, &_rmask, &_gmask, &_bmask, &_amask ); _surface = SDL_CreateRGBSurface( 0, _render_resolution[ 0 ], _render_resolution[ 1 ], _bpp, _rmask, _gmask, _bmask, _amask ); if( !_surface ) { Log( FATAL, "Failed to Create the Screen Surface" ); exit( -1 ); } _texture = SDL_CreateTexture( _renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, _render_resolution[ 0 ], _render_resolution[ 1 ] ); if( !_texture ) { Log( FATAL, "Failed to Create the Screen Texture due to: %s", SDL_GetError() ); exit( -1 ); } _background_color = SDL_MapRGB( _surface->format, _background_color_v[ 0 ], _background_color_v[ 1 ], _background_color_v[ 2 ] ); /* init camera */ /* init mouse */ Log( INFO, "Graphics Initialized" ); }
void Game::Draw() { SDL_RenderClear(m_pRenderer); switch (StateManager::stateMachine->getCurrentGameStates()) { case MENU: m_StartGameMenu.backGroundMenu.Draw(m_pRenderer); for (int iter = 0; iter < 5; iter++) m_StartGameMenu.m_buttonSet[iter].Draw(m_pRenderer); break; case STARTGAME: texture.Draw(m_pRenderer); m_cardLogic.Draw(m_pRenderer); m_Play.Draw(m_pRenderer); m_Bet.Draw(m_pRenderer); m_WIN.Draw(m_pRenderer); m_Credits.Draw(m_pRenderer); m_Menu.Draw(m_pRenderer); //BUTTON MENU level.Draw(m_pRenderer); txt.Draw(m_pRenderer); credit.Draw(m_pRenderer); profit.Draw(m_pRenderer); break; case RULES_OF_GAMES: m_StartGameMenu.backGroundForTeam.DrawRules(m_pRenderer); break; case TEAM_PROJECT: m_StartGameMenu.backGroundForTeam.DrawTeam(m_pRenderer); break; case GAMEOVER: texture.Draw(m_pRenderer); m_Play.Draw(m_pRenderer); m_Bet.Draw(m_pRenderer); m_WIN.Draw(m_pRenderer); m_Credits.Draw(m_pRenderer); m_Menu.Draw(m_pRenderer); level.Draw(m_pRenderer); txt.Draw(m_pRenderer); credit.Draw(m_pRenderer); profit.Draw(m_pRenderer); break; case VIEW_CARDS: if (m_Play.isIsClicked()) { m_cardLogic.GetCardFromDeck(); m_cardLogic.m_TwoCard.clear(); m_Play.setIsClicked(false); } texture.Draw(m_pRenderer); m_Play.Draw(m_pRenderer); m_Bet.Draw(m_pRenderer); m_WIN.Draw(m_pRenderer); m_Credits.Draw(m_pRenderer); m_Menu.Draw(m_pRenderer); //BUTTON MENU m_cardLogic.Draw(m_pRenderer); level.Draw(m_pRenderer); txt.Draw(m_pRenderer); profit.Draw(m_pRenderer); credit.Draw(m_pRenderer); break; } SDL_RenderPresent(m_pRenderer); }/*end of Draw*/
void MoveSprites(SDL_WindowID window, SDL_TextureID sprite) { int i, n; int window_w, window_h; SDL_Rect temp; SDL_Rect *position, *velocity; SDL_SelectRenderer(window); /* Query the sizes */ SDL_GetWindowSize(window, &window_w, &window_h); /* Cycle the color and alpha, if desired */ if (cycle_color) { current_color += cycle_direction; if (current_color < 0) { current_color = 0; cycle_direction = -cycle_direction; } if (current_color > 255) { current_color = 255; cycle_direction = -cycle_direction; } SDL_SetTextureColorMod(sprite, 255, (Uint8) current_color, (Uint8) current_color); } if (cycle_alpha) { current_alpha += cycle_direction; if (current_alpha < 0) { current_alpha = 0; cycle_direction = -cycle_direction; } if (current_alpha > 255) { current_alpha = 255; cycle_direction = -cycle_direction; } SDL_SetTextureAlphaMod(sprite, (Uint8) current_alpha); } /* Draw a gray background */ SDL_SetRenderDrawColor(0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderRect(NULL); /* Test points */ SDL_SetRenderDrawColor(0xFF, 0x00, 0x00, 0xFF); SDL_RenderPoint(0, 0); SDL_RenderPoint(window_w-1, 0); SDL_RenderPoint(0, window_h-1); SDL_RenderPoint(window_w-1, window_h-1); /* Test horizontal and vertical lines */ SDL_SetRenderDrawColor(0x00, 0xFF, 0x00, 0xFF); SDL_RenderLine(1, 0, window_w-2, 0); SDL_RenderLine(1, window_h-1, window_w-2, window_h-1); SDL_RenderLine(0, 1, 0, window_h-2); SDL_RenderLine(window_w-1, 1, window_w-1, window_h-2); /* Test fill and copy */ SDL_SetRenderDrawColor(0xFF, 0xFF, 0xFF, 0xFF); temp.x = 1; temp.y = 1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderRect(&temp); SDL_RenderCopy(sprite, NULL, &temp); temp.x = window_w-sprite_w-1; temp.y = 1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderRect(&temp); SDL_RenderCopy(sprite, NULL, &temp); temp.x = 1; temp.y = window_h-sprite_h-1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderRect(&temp); SDL_RenderCopy(sprite, NULL, &temp); temp.x = window_w-sprite_w-1; temp.y = window_h-sprite_h-1; temp.w = sprite_w; temp.h = sprite_h; SDL_RenderRect(&temp); SDL_RenderCopy(sprite, NULL, &temp); /* Test diagonal lines */ SDL_SetRenderDrawColor(0x00, 0xFF, 0x00, 0xFF); SDL_RenderLine(sprite_w, sprite_h, window_w-sprite_w-2, window_h-sprite_h-2); SDL_RenderLine(window_w-sprite_w-2, sprite_h, sprite_w, window_h-sprite_h-2); /* Move the sprite, bounce at the wall, and draw */ n = 0; for (i = 0; i < num_sprites; ++i) { position = &positions[i]; velocity = &velocities[i]; position->x += velocity->x; if ((position->x < 0) || (position->x >= (window_w - sprite_w))) { velocity->x = -velocity->x; position->x += velocity->x; } position->y += velocity->y; if ((position->y < 0) || (position->y >= (window_h - sprite_h))) { velocity->y = -velocity->y; position->y += velocity->y; } /* Blit the sprite onto the screen */ SDL_RenderCopy(sprite, NULL, position); } /* Update the screen! */ SDL_RenderPresent(); }
int main(int argc, char *argv[]) { #ifdef _WIN32 /*Initialise SDL needed for desktop*/ if (SDL_Init(SDL_INIT_VIDEO) < 0) //Check SDL initialisation { //Failed initialisation SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL"); return -1; } #endif /*Initialise SDL_ttf*/ if (TTF_Init() < 0) /*Check SDL_ttf initialisation*/ { /*Failed initialisation*/ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_ttf"); return -1; } /*Initialise SDL_mixer*/ Mix_Init(MIX_INIT_OGG); if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { /*Failed initialisation*/ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_Mixer"); return -1; } /*Initialize PNG loading*/ int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { /*Failed initialisation*/ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_image"); return -1; } /*Time Check*/ unsigned int lastTime = SDL_GetTicks(); SDL_Window* window; SDL_Renderer* renderer; int winWidth; int winHeight; #ifdef __ANDROID__ if(SDL_CreateWindowAndRenderer(0, 0, 0, &window, &renderer) < 0) exit(2); SDL_GetWindowSize(window, &winWidth, &winHeight); #elif _WIN32 /*Create Window*/ int winPosX = 100; int winPosY = 100; winWidth = 640; winHeight = 480; window = SDL_CreateWindow("MGPDemoAudio", /*The first parameter is the window title*/ winPosX, winPosY, winWidth, winHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); /*Create Renderer from the window*/ renderer = SDL_CreateRenderer(window, -1, 0); #endif /*setup state manager*/ JAM_StateManager * stateManager = new JAM_StateManager(); /*set the initial state*/ stateManager->addState(new Game(stateManager, renderer, winWidth, winHeight)); /*Start Game Loop*/ bool go = true; while (go) { /*Time Check*/ unsigned int current = SDL_GetTicks(); float deltaTime = (float)(current - lastTime) / 1000.0f; lastTime = current; /*handle the current state inputs*/ go = stateManager->input(); /*update the current state*/ stateManager->update(deltaTime); /*set draw colour to white*/ SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); /*Clear the entire screen to the set colour*/ SDL_RenderClear(renderer); /*draw the states*/ stateManager->draw(); /*display renderer*/ SDL_RenderPresent(renderer); /*Time Limiter*/ if (deltaTime < (1.0f / 50.0f)) { SDL_Delay((unsigned int)(((1.0f / 50.0f) - deltaTime)*1000.0f)); } } /*destroy data*/ delete stateManager; SDL_DestroyWindow(window); SDL_Quit(); exit(0); return 0; }