Gremlin92
@Gremlin92
Целеустремленный

Можно ли подружить glubuild2dmipmaps и qt?

Короче не пойму в чем ошибка - вероятно что код из qt в неправильном порядке либо еще что-то. Проблема рисует белый экран с кнопками а текстуры не накладываются
#include "Scene1.h"
#include <QtWidgets/QApplication>
#include "MyWidget.h"
void main(int argc,char*argv[])
{
        QApplication a(argc, argv);
	QWidget qw;
	MyWidget mw(&qw);
	ilInit();
	iluInit();
	Scene1_ = new Scene1();
	Scene1_->LoadWelcome();
	mw.SetElements(Scene1_);
	mw.show();
	a.exec();
}
//class MyWidget.h
#pragma once
#include <QtGui/QtGui>
#include <QtWidgets/QtWidgets>
#include <QtWidgets/QPushButton>
#include "Scene1.h"
class MyWidget
    :  public QOpenGLWidget
{
  // Q_OBJECT
public:
    MyWidget(QWidget* parent);
    void initializeGL();
    void resizeGL(int nWidth, int nHeight);
    void paintGL();
    void SetElements(Scene1*Scene1_);
    void Show();
private:
    std::vector<QPushButton*> m_button;
    Scene1* Scene1_;

};

#include "MyWidget.h"
#pragma comment(lib,"Qt5Cored.lib")
#pragma comment(lib,"Qt5Guid.lib")
#pragma comment(lib,"Qt5Widgetsd.lib")
#pragma comment(lib,"Qt5OpenGLd.lib")
#pragma comment(lib,"Qt5OpenGLExtensionsd.lib")
#pragma comment(lib,"OpenGL32.lib")
MyWidget::MyWidget(QWidget* parent) // конструктор
{
    this->setWindowTitle(QString("Welcome"));
    resize(700, 500); // задаем размеры окна
	m_button.push_back(new QPushButton("My Button1", this));
	m_button.push_back(new QPushButton("My Button2", this));
	m_button.push_back(new QPushButton("My Button3", this));
	m_button.push_back(new QPushButton("My Button4", this));
	m_button.push_back(new QPushButton("My Button5", this));
	m_button.push_back(new QPushButton("My Button6", this));
	m_button.push_back(new QPushButton("My Button7", this));
	m_button.push_back(new QPushButton("My Button8", this));
	m_button.push_back(new QPushButton("My Button9", this));
	m_button.push_back(new QPushButton("My Button10",this));
    m_button[0]->setGeometry(QRect(QPoint(50, 400), QSize(100, 50)));
    m_button[1]->setGeometry(QRect(QPoint(170, 400), QSize(100, 50)));
    m_button[2]->setGeometry(QRect(QPoint(290, 400), QSize(100, 50)));
    m_button[3]->setGeometry(QRect(QPoint(410, 400), QSize(100, 50)));
    m_button[4]->setGeometry(QRect(QPoint(530, 400), QSize(100, 50)));
    QObject::connect(m_button[0], &QPushButton::clicked, [=]() {
        m_button[0]->setText("Example1");
        });
	
    QObject::connect(m_button[1], &QPushButton::clicked, [=]() {
        m_button[1]->setText("Example2");
        });
    QObject::connect(m_button[2], &QPushButton::clicked, [=]() {
        m_button[2]->setText("Example3");
        });
    QObject::connect(m_button[3], &QPushButton::clicked, [=]() {
        m_button[3]->setText("Example4");
        });

    QObject::connect(m_button[4], &QPushButton::clicked, [=]() {
        m_button[4]->setText("Example5");
        });
}

void MyWidget::initializeGL()
{
    QOpenGLFunctions* f = QOpenGLContext::currentContext()->functions();
    f->glClearColor(0,0,0,0); // заполняем экран белым цветом
    gluLookAt(0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
}

void MyWidget::resizeGL(int nWidth, int nHeight)
{
    glViewport(0, 0, nHeight, nHeight); // установка точки обзора
}

void MyWidget::SetElements(Scene1* Scene1__)
{
	this->Scene1_ = Scene1__;
}
void MyWidget::Show()
{
	glColor4f(1,0,0,0);
	glBegin(GL_QUADS);
	glVertex3f(0.5, 0.5, 0.5);
	glVertex3f(-0.5, 0.5, 0.5);
	glVertex3f(-0.5, -0.5, 0.5);
	glVertex3f(0.5, -0.5, 0.5);
	glEnd();
}
void MyWidget::paintGL() // рисование
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_TEXTURE_2D);
	//Show();
	Scene1_->ShowWelcome(true);
}

//class Scene1.h
#ifndef OGL
	#define OGL
#ifdef _WIN32
    #include <Window.h>
#endif // _WIN32
#include <fstream>
#include <GL/gl.h>
#include <GL/glu.h>
#include <IL/il.h>
#include <IL/ilu.h>
#ifdef __unix__
    #include <cstring>
#else
#pragma comment(lib,"OpenGL32.lib")
#pragma comment(lib,"Glu32.lib")
#pragma comment(lib,"ILU.lib")
#pragma comment(lib,"DevIl.lib")
#pragma comment(lib,"SDL2.lib")
#endif
struct Image
{
	float**VertexCoordinats;
	unsigned int*IndexTexture;
	std::string *Name;
	int *number;
};
struct Image_s
{
	float Xleft;
	float Xright;
	float Yup;
	float Ydown;
	float Z;
	unsigned int IndexTexture;
	std::string Name;
	int number;
	bool alpha;
};
class Scene1
{
public:
	Scene1(void);
	void ShowWelcome(bool show);
	void LoadWelcome();//numbers

	void EnableTexture(Image_s im, bool third,bool alpha);
	int FindTexture(std::string name, std::vector<Image_s> vec);
	int err;
#ifndef _WIN32
	const char* strError;
#else
	wchar_t* strError;
#endif
	int width;
	int height;
	unsigned int type;
	unsigned char* copyData;	
        std::ofstream flogout;
	int CountIndexTexture;
        Image* image;
	static const int CountTexture = 58;
	std::vector<Image_s> welcomev;
	int AnimateBar;
	std::string NameAnimateBar;
};
//Scene.cpp
#include "Scene1.h"
#ifdef __unix__
#include <stdlib.h>
#include <unistd.h>
#endif
Scene1::Scene1(void)
{
	AnimateBar = 0;
	image = new Image[CountTexture];
	image->VertexCoordinats = new float* [CountTexture];
	image->Name = new std::string[CountTexture];
	for (int i = 0; i < CountTexture; i++)
	{
		image->VertexCoordinats[i] = new float[4];
		image->Name[i] = "";
	}
	image->IndexTexture = new unsigned int[CountTexture];
	image->number = new int[CountTexture];
	CountIndexTexture = 0;
	AnimateBar = 0;
	flogout.open("log.txt");
}
unsigned int Scene1::LoadImage(const ILstring path)
{
	ILenum ext;
	if (strstr(reinterpret_cast<const char*>(path), "png"))
		ext = IL_PNG;
	if (strstr(reinterpret_cast<const char*>(path), "jpg") || strstr(reinterpret_cast<const char*>(path), "jpeg"))
		ext = IL_JPG;
	if (strstr(reinterpret_cast<const char*>(path), "bmp"))
		ext = IL_BMP;
	if (strstr(reinterpret_cast<const char*>(path), "gif"))
		ext = IL_GIF;

	ilLoad(ext, reinterpret_cast<const ILstring>(path));
	err = ilGetError();
	if (err != IL_NO_ERROR) {
#ifdef _WIN32
		strError = (wchar_t *)iluErrorString(err);
#else
		strError = iluErrorString(err);
#endif
#ifdef _WIN32
		MessageBox(NULL, NULL, L"Ошибка при загрузке il!", MB_OK);
#endif
		flogout << "Error loading image: " << reinterpret_cast<const char*>(path) << std::endl;
 		std::cout<< "Error loading image: " << reinterpret_cast<const char*>(path)<<std::endl;
#ifndef _WIN32
		long size;
        char*buf,*ptr;
        size=pathconf(".",_PC_PATH_MAX);
        buf = (char*)malloc((size_t)size);
        ptr=getcwd(buf,(size_t)size);
		std::cout<< ptr<<std::endl;
#endif
		flogout.close();
		exit(EXIT_FAILURE);
	}
	width = ilGetInteger(IL_IMAGE_WIDTH);
	height = ilGetInteger(IL_IMAGE_HEIGHT);
	type = ilGetInteger(IL_IMAGE_FORMAT);
	copyData = ilGetData();
	image->IndexTexture[CountIndexTexture] = 0;
	glGenTextures(1, &image->IndexTexture[CountIndexTexture]);

	glBindTexture(GL_TEXTURE_2D, image->IndexTexture[CountIndexTexture]);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	gluBuild2DMipmaps(GL_TEXTURE_2D, type, width, height, type, GL_UNSIGNED_BYTE, copyData);
	
	return image->IndexTexture[CountIndexTexture++];
};
void Scene1::LoadWelcome()
{
	std::ifstream in("welcome coordinats.txt");
	Image_s im;
	if (in.is_open())
	{
		std::string path__;
		while ((in >> path__) && (in >> im.Xright) && (in >> im.Xleft) && (in >> im.Ydown) && (in >> im.Yup) && (in >> im.Z) && (in >> im.alpha))
		{
			im.IndexTexture = LoadImage(reinterpret_cast<const ILstring>(path__.c_str()));
			path__ = path__.substr(path__.find_last_of("/\\") + 1);
			size_t dot_i = path__.find_last_of('.');
			im.Name = path__.substr(0, dot_i);
			im.number = welcomev.size();
			welcomev.push_back(im);
		}
	}
	in.close();
}
void Scene1::ShowWelcome(bool show)
{
	if (!show)
		return;
	glEnable(GL_ALPHA_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	int numb = FindTexture("welcome",welcomev);
	EnableTexture(welcomev[numb],true,true);

	numb = FindTexture("logo", welcomev);
	EnableTexture(welcomev[numb],true,true);

	if (AnimateBar>1)
		AnimateBar = 0;
	NameAnimateBar = "bar";

	std::stringstream out;
	out << AnimateBar;
	NameAnimateBar += out.str();
	{
		numb = FindTexture(NameAnimateBar, welcomev);
		EnableTexture(welcomev[numb],true,true);
	}
	NameAnimateBar.clear();
	AnimateBar++;
	glDisable(GL_BLEND);
	glDisable(GL_ALPHA_TEST);
}
void Scene1::EnableTexture(Image_s im, bool third, bool alpha)
{
	glBindTexture(GL_TEXTURE_2D, im.IndexTexture);
	if (alpha)
	{
		glEnable(GL_ALPHA_TEST);
		glEnable(GL_BLEND);
	}
	glBegin(GL_QUADS);
	glTexCoord2f(1.0f, 1.0f);
	if (!third)
		glVertex2f(im.Xright, im.Yup);
	else
		glVertex3f(im.Xright, im.Yup, im.Z);
	glTexCoord2f(0.0f, 1.0f);
	if (!third)
		glVertex2f(im.Xleft, im.Yup);
	else
		glVertex3f(im.Xleft, im.Yup, im.Z);
	glTexCoord2f(0.0f, 0.0f);
	if (!third)
		glVertex2f(im.Xleft, im.Ydown);
	else
		glVertex3f(im.Xleft, im.Ydown, im.Z);
	glTexCoord2f(1.0f, 0.0f);
	if (!third)
		glVertex2f(im.Xright, im.Ydown);
	else
		glVertex3f(im.Xright, im.Ydown, im.Z);
	glEnd();
	if (alpha)
	{
		glDisable(GL_ALPHA_TEST);
		glDisable(GL_BLEND);
	}
}
int Scene1::FindTexture(std::string name, std::vector<Image_s> vec)
{
	int result = -1,size = vec.size();
	for (int i = 0; i < size; i++)
		if (strcmp(vec[i].Name.c_str(), name.c_str()) == 0)
		{
			result = i;
			break;
		}
	return result;
}

welcome coordinats.txt
content//welcome.jpg
1
-1
1
-1
0
1
content//logo.png
0.8
-0.8
0.8
0.4
0.99
1
content//progress//bar0.png
0.4
-0.4
-0.4
-0.8
1
1
content//progress//bar1.png
0.4
-0.4
-0.4
-0.8
1
1
  • Вопрос задан
  • 21 просмотр
Пригласить эксперта
Ответы на вопрос 1
Gremlin92
@Gremlin92 Автор вопроса
Целеустремленный
Короче как я понял надо переписать на qt загрузку изображений из LoadWelcome() через qimage и ShowWelcome() тоже придется переписать на qtшный bind() такого вида
QOpenGLTexture* texture;
    QImage image1;
void MyWidget::initializeGL()
{
	//QOpenGLContext* ctx = new QOpenGLContext();
    QOpenGLFunctions* f = QOpenGLContext::currentContext()->functions();
    f->glClearColor(0,0,0,0); // заполняем экран белым цветом
    glEnable(GL_DEPTH_TEST); // задаем глубину проверки пикселей
    glShadeModel(GL_FLAT); // убираем режим сглаживания цветов
    glEnable(GL_CULL_FACE); // говорим, что будем строить только внешние поверхности
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // фигуры будут закрашены с обеих сторон
	gluLookAt(0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
	image1.load("welcome.png"); // загружаем изображение в переменную image1
	// конвертируем изображение в формат для работы с OpenGL:
	texture = new QOpenGLTexture(image1.mirrored());
	texture->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear);
	texture->setMagnificationFilter(QOpenGLTexture::Linear);
}
void MyWidget::Show()
{
	texture->bind();
	//glColor4f(1,0,0,0); // задаем цвет
	glBegin(GL_QUADS); // говорим, что рисовать будем прямоугольник
	// задаем вершины многоугольника
	glTexCoord2f(1, 1);
	glVertex2f(0.5, 0.5);
	glTexCoord2f(0, 1);
	glVertex2f(-0.5, 0.5);
	glTexCoord2f(0, 0);
	glVertex2f(-0.5, -0.5);
	glTexCoord2f(1, 0);
	glVertex2f(0.5, -0.5);
	glEnd();
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 03:52
1000 руб./за проект
19 апр. 2024, в 03:01
1000 руб./за проект
18 апр. 2024, в 21:56
2000 руб./за проект