2016-09-02 2 views
0

SDL не отображает ничего после того, как я завернул структуру текстуры. Первый обертку - от lazyfoo.net, который работал. Обертка этого, чтобы сделать его еще проще, ничего не отображала. Полный код приведен ниже:SDL не отображает изображения после обертывания структуры

#pragma once 
    #include <vector> 
    #include <map> 
    #include "LTexture.h"` 
    #include "Rect.h" 

    using namespace std; 
    //Wrapper for the wrapper class LTexture 
    class Drawable { 
     LTexture* texture = nullptr; 
     SDL_Rect* clip = nullptr; 
     map<string, SDL_Rect*> images; 
     int x1; 
     int y1; 
     int x2; 
     int y2; 
     int imagex; 
     int imagey; 
     void TextInit(string path) { 
      texture = new LTexture(path); 
     } 
     void utilSet2(int iw, int ih) { 
      x2 = iw + x1; 
      y2 = ih + y1; 
     } 
    public: 
     Drawable(int wx, int wy, string path) : x1(wx), y1(wy){ 
      clip = new SDL_Rect; //Create it 
      TextInit(path); 
     } 
     //For background images and images with just one texture 
     Drawable(string path, int imagew, int imageh): x1(0),                       y1(0),x2(imagew),y2(imageh) { 
      TextInit(path); 
      addNullClip("null"); 
      setCurrentClip("null"); 
     } 

     //Add a clip and set its name. 
     void addClip(int x, int y, int width, int height, string name) { 
      SDL_Rect* newclip = new SDL_Rect; 
      newclip->x = x; 
      newclip->y = y; 
      newclip->w = width; 
      newclip->h = height; 
      images[name] = newclip; 
     } 
     void addNullClip(string name) { 
      SDL_Rect* newclip = nullptr; 
      images[name] = newclip; 
     } 
     //Set the current clip with its string name 
     void setCurrentClip(string name) { 
      delete clip; //deallocate clip 
      clip = images[name]; 
      if (clip != nullptr) { 
      x2 = clip->w + x1; 
      y2 = clip->h + y1; 
      } 
      else { 

      } 
     } 
     //Draw it to the screen 
     void render() { 
      texture->render(x1, y1,clip); 
     } 
     void move(int lroffset, int udoffset) { 
      x1 += lroffset; 
      x2 += lroffset; 
      y1 += udoffset; 
      y2 += udoffset; 
     } 
     Rect getCoords() { 
     Rect r; 
     r.f.x = x1; 
     r.f.y = y1; 
     r.s.x = x2; 
     r.s.y = y2; 
     return r; 
     } 

    }; 
    //For when you don't wanna type Drawable 
    typedef Drawable d; 
    //Same as d, but just in case 
    typedef Drawable D; 

Это он. Я создаю несколько экземпляров, и он ничего ... ничего (кроме отображения экрана). Так что я слева задает вопрос о том, почему не этот код работать :(Да, и в случае, если вам это нужно, вот это класс LTexture из lazyfoo.net:.

#pragma once 
    //Using SDL, SDL_image, standard IO, and strings 
    #include <SDL.h> //SDL header file 
    #include <SDL_image.h> //SDL image file 
    #include <stdio.h> //standard C ouput 
    #include <string> //standard c++ string 
    //Texture wrapper class 
    class LTexture 
    { 
    public: 
    //Initializes variables 
     LTexture(std::string path); 
     LTexture(); 
     //Deallocates memory 
     ~LTexture(); 

     //Loads image at specified path 
     bool loadFromFile(std::string path); 

     //Deallocates texture 
     void free(); 

     //Renders texture at given point 
     void render(int x, int y, SDL_Rect* clip); 

     //Gets image dimensions 
     int getWidth() const; 
     int getHeight() const; 

    private: 
     //The actual hardware texture 
     SDL_Texture* mTexture; 

     //Image dimensions 
     int mWidth; 
     int mHeight; 
    }; 

    //LTexture.cpp file 

    #include "LTexture.h" 
    extern SDL_Renderer* gRenderer; 
    LTexture::LTexture(std::string path) 
    { 
     bool loop = true; 
     //Load texture 
     if (!loadFromFile(path)) 
     { 
      printf("Couldn't load the image"); 
     } 

    } 
    LTexture::LTexture() 
    { 
     //Initialize 
     mTexture = NULL; 
     mWidth = 0; 
     mHeight = 0; 
    } 

    LTexture::~LTexture() 
    { 
     //Deallocate 
     free(); 
    } 

    bool LTexture::loadFromFile(std::string path) 
    { 
     //Get rid of preexisting texture 
     free(); 

     //The final texture 
     SDL_Texture* newTexture = NULL; 

//Load image at specified path 
SDL_Surface* loadedSurface = IMG_Load(path.c_str()); 
     if (loadedSurface == NULL) 
     { 
      printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); 
     } 
     else 
     { 
      //Color key image 
      SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0, 0xFF, 0xFF)); 

      //Create texture from surface pixels 
      newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface); 
      if (newTexture == NULL) 
      { 
       printf("Unable to create texture from %s! SDL Error: %s\n",         path.c_str(), SDL_GetError()); 
      } 
      else 
      { 
       //Get image dimensions 
       mWidth = loadedSurface->w; 
        mHeight = loadedSurface->h; 
      } 

       //Get rid of old loaded surface 
       SDL_FreeSurface(loadedSurface); 
      } 

      //Return success 
      mTexture = newTexture; 
      return mTexture != NULL; 
     } 

     void LTexture::free() 
      { 
      //Free texture if it exists 
      if (mTexture != NULL) 
      { 
       SDL_DestroyTexture(mTexture); 
       mTexture = NULL; 
       mWidth = 0; 
       mHeight = 0; 
      } 
     } 

     void LTexture::render(int x, int y, SDL_Rect* clip) 
     { 
      if (clip != nullptr) { 
       //Set rendering space with the clip's width and height and render to screen 
       SDL_Rect renderQuad = { x, y, clip->w, clip->h }; 
       SDL_RenderCopy(gRenderer, mTexture, NULL, &renderQuad); 
      } 
      else 
      { 
       //Set rendering space and render to screen 
       SDL_Rect renderQuad = { x, y, mWidth, mHeight }; 
       SDL_RenderCopy(gRenderer, mTexture, NULL, &renderQuad); 
      } 
     } 

     int LTexture::getWidth() const 
     { 
      return mWidth; 
     } 

     int LTexture::getHeight() const 
     { 
      return mHeight; 
     } 

Не могли бы вы сказать мне, что я сделал не так, как я могу это исправить, и почему он ничего не отображает. И если кто-нибудь спросит, все правильно связано. Редактировать: я установил интервал и добавил две вещи ниже (что вам нужно полностью понять .) точка структура:

#pragma once 
struct Point { 
    int x; 
    int y; 
}; 
bool operator== (Point one, Point two) { 
    if (one.x == two.x && one.y == two.y) { 
     return true; 
    } 
    else { 
     return false; 
    } 
} 

и

#pragma once 
#include "Point.h" 
struct Rect { 
    Point f; 
    Point s; 
}; 
//Helper to make my life and yours easier 
bool operator==(Rect one, Rect two) { 
    bool returnval = false; 
    int i; 
    int j; 
    for (i = one.f.x; i < one.s.x; i++) { 
     for (j = one.f.y; j < one.s.y; j++) { 
      Point checker; 
      checker.x = i; 
      checker.y = j; 

      if (two.f == checker || two.s == checker) { 
       returnval = true; 
      } 
     } 
    } 
    return returnval; 
} 
+0

Части кода, которые вы показываете, на самом деле не читабельны (непостоянный отступ, чересчур длинные линии с преимущественно белым пространством). Пожалуйста, переформатируйте его. –

+0

Я попробую (здесь мне сложно сделать код). – TheBeginningProgrammer

+0

Самый простой способ поставить код в вопрос (или ответ) - просто скопировать-вставить его, затем пометить его и перейти на панель инструментов и нажать кнопку «код» ('{}'). Не пытайтесь переписать существующий код в вопросы (или ответы), поскольку это может добавить ошибки, не связанные с вопросом, или, может быть, даже * исправить * ошибку, о которой вы хотите спросить, не заметив этого. –

ответ

0

Благодаря вашей помощи (нет), я выяснил сбой в классе LTexture. Это был запутанный глюк в функции рендеринга. Для всех, кто хочет знать, здесь:

void Texture::render() 
{ 
    //Set rendering space and render to screen 
    SDL_Rect renderQuad = { x, y, mWidth, mHeight }; 
    //Set clip rendering dimensions 
    if (clip != NULL) 
    { 
     renderQuad.w = clip->w; 
     renderQuad.h = clip->h; 
    } 
SDL_RenderCopy(Renderer, mTexture, clip, &renderQuad); 

}

я делал:

SDL_Rect renderQuad = { x, y, clip->w, clip->h }; 

Который не будет оказывать. Итак, это все.

Смежные вопросы