Форум программистов, компьютерный форум, киберфорум
C++
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/5: Рейтинг темы: голосов - 5, средняя оценка - 5.00
0 / 0 / 0
Регистрация: 13.10.2022
Сообщений: 3

LNK2019 когда пытаюсь использовать функцию из другого файла

14.10.2022, 23:34. Показов 1117. Ответов 3

Студворк — интернет-сервис помощи студентам
я пытаюсь импортировать код из другого файла cpp, но сталкиваюсь с ошибками наподобие таких:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: class Shader & __thiscall Shader::Use(void)" (?Use@Shader@@QAEAAV1@XZ) referenced in function "public: void __thiscall TextRenderer::RenderText(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,float,float,float,struct glm::vec<3,float,0>)" (?RenderText@TextRenderer@@QAEXV?$basic_ string@DU?$char_traits@D@std@@V?$allocat or@D@2@@std@@MMMU?$vec@$02M$0A@@glm@@@Z)

как это исправить? я не понимаю в чём проблема


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#include <glad/glad.h>
#include <GLFW/glfw3.h>
 
#include <iostream>
#include "Shaders.h"
#include "stb_image.h"
 
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <ft2build.h>
#include <freetype.h>
#include <text_renderer.h>
#include <map>
#include "Character.h"
 
 
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);
void kickInput(GLFWwindow* window, float& dt, int& timer);
void checkForX(float(&offsets)[3], bool(&flags)[3], float(&heights)[6], float& yoffset, int& score, bool& game_state);
void calculateHeight(float(&offsets)[3], float(&heights)[6], bool(&flags)[3]);
void RenderText(Shader& shader, std::string text, float x, float y, float scale, glm::vec3 color);
 
 
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
 
 
 
GLuint VBO[4], VAO[4], EBO[4];
 
int main()
{
 
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
 
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
 
 
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
 
 
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }
 
 
    glGenVertexArrays(4, VAO);
    glGenBuffers(4, VBO);
    glGenBuffers(4, EBO);
 
 
    TextRenderer* Text;
    Text = new TextRenderer(800, 600);
    Text->Load("fonts/ocraext.TTF", 24);
 
 
 
 
    // configure VAO/VBO for texture quads
    // -----------------------------------
    glBindVertexArray(VAO[3]);
    glBindBuffer(GL_ARRAY_BUFFER, VBO[3]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[3]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
    std::cout << glGetError() << std::endl;
 
 
 
 
    Shader ourShader("Game/shaders/3.3.shader.vs", "Game/shaders/3.3.shader.fs"); // you can name your shader files however you like
    Shader pipe1("Game/shaders/pipe1.vs", "Game/shaders/pipe1.fs"); // you can name your shader files however you like
    Shader pipe2("Game/shaders/pipe2.vs", "Game/shaders/pipe2.fs"); // you can name your shader files however you like
 
 
 
    float pipes[] = {
        // positions          // colors           // texture coords
         1.0f,  2.5f, 0.0f,   0.0f, 1.0f, 0.0f,    // top right
         1.0f,  0.25f, 0.0f,   0.0f, 1.0f, 0.0f,   // bottom right
         0.5f, 0.25f, 0.0f,    0.0f, 1.0f, 0.0f,   // bottom left
         0.5f,  2.5f, 0.0f,   0.0f, 1.0f, 0.0f,   // top left 
    };
    float pipes2[] = {
        // positions          // colors           // texture coords
         1.0f,  -2.5f, 0.0f,   0.0f, 1.0f, 0.0f,    // top right
         1.0f,  -0.25f, 0.0f,   0.0f, 1.0f, 0.0f,   // bottom right
         0.5f, -0.25f, 0.0f,    0.0f, 1.0f, 0.0f,   // bottom left
         0.5f,  -2.5f, 0.0f,   0.0f, 1.0f, 0.0f,   // top left 
    };
    unsigned int pipesindices[] = {
        0, 1, 3,
        1, 2, 3
    };
 
    float vertices[] = {
        // positions          // colors           // texture coords
         0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f, // top right
         0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f, // bottom right
        -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f, // bottom left
        -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f  // top left 
    };
    unsigned int indices[] = {
        0, 1, 3,
        1, 2, 3
    };
 
 
    glBindVertexArray(VAO[0]);
    glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);
 
 
    unsigned int texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    // set the texture wrapping/filtering options (on the currently bound texture object)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load and generate the texture
    int width, height, nrChannels;
    unsigned char* data = stbi_load("Game/container.jpg", &width, &height, &nrChannels, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
    std::cout << glGetError() << std::endl;
 
 
    glBindVertexArray(VAO[1]);
    glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(pipes), pipes, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[1]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(pipesindices), pipesindices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    std::cout << glGetError() << std::endl;
 
    glBindVertexArray(VAO[2]);
    glBindBuffer(GL_ARRAY_BUFFER, VBO[2]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(pipes2), pipes2, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[2]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(pipesindices), pipesindices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    std::cout << glGetError() << std::endl;
 
 
    float offsets[3];
    float yoffset = -0.0f;
    float boostFall = 0.0025f;
    float velocityUp = 0.5f;
    float dt = 0;
    int timer = 0;
    float whitespace = .5f;
    float heights[6];
    bool flags[3];
    int score = 0;
    flags[0] = false;
 
    offsets[0] = 1.0f;
    bool game_state = true;
 
 
 
 
 
 
    while (!glfwWindowShouldClose(window))
    {
        // input
        // -----
        processInput(window);
        calculateHeight(offsets, heights, flags);
        checkForX(offsets, flags, heights, yoffset, score, game_state);
        kickInput(window, dt, timer);
        if (yoffset <= -10 || game_state == false) {
            //break;
        }
 
        // render
        // ------
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
 
 
        dt++;
        timer++;
        yoffset -= boostFall * dt;
 
        //offsets[0] -= 0.001f;
        offsets[0] -= 0.005f;
 
 
 
 
 
        glm::mat4 trans = glm::mat4(1.0f);
        trans = glm::scale(trans, glm::vec3(0.1, 0.1, 0.1));
        unsigned int transformLoc = glGetUniformLocation(ourShader.ID, "transform");
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans));
        glBindVertexArray(VAO[0]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        ourShader.setFloat("yOffset", yoffset);
        ourShader.use();
        //std::cout << glGetError() << std::endl;
 
 
 
 
        glm::mat4 trans2 = glm::mat4(1.0f);
        trans2 = glm::scale(trans2, glm::vec3(1, 1, 1));
        trans2 = glm::translate(trans2, glm::vec3(.0f, heights[0], .0f));
        unsigned int transformLoc2 = glGetUniformLocation(pipe1.ID, "transform");
        glUniformMatrix4fv(transformLoc2, 1, GL_FALSE, glm::value_ptr(trans2));
        glBindVertexArray(VAO[1]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        pipe1.setFloat("xOffset", offsets[0]);
        pipe1.use();
        //std::cout << glGetError() << std::endl;
 
 
        glm::mat4 trans3 = glm::mat4(1.0f);
        trans3 = glm::scale(trans3, glm::vec3(1, 1, 1));
        trans3 = glm::translate(trans3, glm::vec3(.0f, heights[1], .0f));
        unsigned int transformLoc3 = glGetUniformLocation(pipe2.ID, "transform");
        glUniformMatrix4fv(transformLoc3, 1, GL_FALSE, glm::value_ptr(trans3));
        glBindVertexArray(VAO[2]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        pipe2.setFloat("xOffset", offsets[0]);
        pipe2.use();
        //std::cout << glGetError() << std::endl;
 
        std::string text = "Score: " + std::to_string(score);
 
        Text->RenderText("Lives:", 5.0f, 5.0f, 1.0f);
 
        //RenderText(shader, text, 25.0f, 25.0f, 1.0f, glm::vec3(0.5, 0.8f, 0.2f));
        //RenderText(shader, "(C) LearnOpenGL.com", 540.0f, 570.0f, 0.5f, glm::vec3(0.3, 0.7f, 0.9f));
        //std::cout << glGetError() << std::endl;
 
 
 
 
        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
 
    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(4, VAO);
    glDeleteBuffers(4, VBO);
 
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}
 
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow* window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}
 
void calculateHeight(float(&offsets)[3], float(&heights)[6], bool(&flags)[3])
{
    float rndm1 = (rand() % 700 + 1); // 0.6
    int rndm2 = rand() % 2 + 1;
 
    if (rndm2 == 1) {
        rndm1 = (rndm1 / 1000);
    }
    else {
        rndm1 = -(rndm1 / 1000);
    }
 
    if (offsets[0] > 0.9f) { // first
        heights[0] = rndm1;
        heights[1] = rndm1;
    }
    if (offsets[1] > 0.9f) { // second
        heights[2] = rndm1;
        heights[3] = rndm1;
    }
    if (offsets[2] > 0.9f) { // third
        heights[4] = rndm1;
        heights[5] = rndm1;
    }
}
 
void checkForX(float(&offsets)[3], bool(&flags)[3], float(&heights)[6], float& yoffset, int& score, bool& game_state)
{
    if (offsets[0] <= -2.0f) {
        offsets[0] = 1.0f;
        flags[0] = false;
    }
    if (offsets[1] <= -1.0f) {
        offsets[1] = -0.5f;
    }
    if (offsets[2] <= -1.0f) {
        offsets[2] = -0.5f;
    }
    //std::cout << offsets[0] << std::endl;
    if (offsets[0] <= -0.4f && offsets[0] >= -1.05f) {
        //std::cout << heights[0]+0.25 << "  " << yoffset / 10 << "  " << heights[1] - 0.25 << std::endl;
        if (yoffset / 10 > heights[0] + 0.21 || yoffset / 10 < heights[1] - 0.21) {
            game_state = false;
        }
 
    }
    if (offsets[0] <= -1.1f && flags[0] == false) {
        score++;
        std::cout << score << std::endl;
        flags[0] = true;
    }
    //if (offsets[1] <= -0.4f && offsets[0] >= -1.05f) {
    //    if (yoffset / 10 > heights[2] + 0.25 || yoffset / 10 < heights[3] - 0.25) {
    //        std::cout << "hitted";
    //    }
    //}
    //if (offsets[2] <= -0.4f && offsets[0] >= -1.05f) {
    //    if (yoffset / 10 > heights[4] + 0.25 || yoffset / 10 < heights[5] - 0.25) {
    //        std::cout << "hitted";
    //    }
    //}
 
}
 
void kickInput(GLFWwindow* window, float& dt, int& timer)
{
    if (timer >= 30) {
        if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) {
            dt = -30;
            timer = 0;
        }
    }
 
 
}
 
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and 
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}
texture.h:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#pragma once
 
#ifndef TEXTURE_H
#define TEXTURE_H
 
#include <glad/glad.h>
 
// Texture2D is able to store and configure a texture in OpenGL.
// It also hosts utility functions for easy management.
class Texture2D
{
public:
    // holds the ID of the texture object, used for all texture operations to reference to this particlar texture
    unsigned int ID;
    // texture image dimensions
    unsigned int Width, Height; // width and height of loaded image in pixels
    // texture Format
    unsigned int Internal_Format; // format of texture object
    unsigned int Image_Format; // format of loaded image
    // texture configuration
    unsigned int Wrap_S; // wrapping mode on S axis
    unsigned int Wrap_T; // wrapping mode on T axis
    unsigned int Filter_Min; // filtering mode if texture pixels < screen pixels
    unsigned int Filter_Max; // filtering mode if texture pixels > screen pixels
    // constructor (sets default texture modes)
    Texture2D();
    // generates texture from image data
    void Generate(unsigned int width, unsigned int height, unsigned char* data);
    // binds the texture as the current active GL_TEXTURE_2D texture object
    void Bind() const;
};
 
#endif
text.renderer.cpp:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
 
#include <glm/gtc/matrix_transform.hpp>
#include <ft2build.h>
#include FT_FREETYPE_H
 
#include "text_renderer.h"
#include "resource_manager.h"
 
 
TextRenderer::TextRenderer(unsigned int width, unsigned int height)
{
    // load and configure shader
    this->TextShader = ResourceManager::LoadShader("text_2d.vs", "text_2d.fs", nullptr, "text");
    this->TextShader.SetMatrix4("projection", glm::ortho(0.0f, static_cast<float>(width), static_cast<float>(height), 0.0f), true);
    this->TextShader.SetInteger("text", 0);
    // configure VAO/VBO for texture quads
    glGenVertexArrays(1, &this->VAO);
    glGenBuffers(1, &this->VBO);
    glBindVertexArray(this->VAO);
    glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}
 
void TextRenderer::Load(std::string font, unsigned int fontSize)
{
    // first clear the previously loaded Characters
    this->Characters.clear();
    // then initialize and load the FreeType library
    FT_Library ft;
    if (FT_Init_FreeType(&ft)) // all functions return a value different than 0 whenever an error occurred
        std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl;
    // load font as face
    FT_Face face;
    if (FT_New_Face(ft, font.c_str(), 0, &face))
        std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl;
    // set size to load glyphs as
    FT_Set_Pixel_Sizes(face, 0, fontSize);
    // disable byte-alignment restriction
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    // then for the first 128 ASCII characters, pre-load/compile their characters and store them
    for (GLubyte c = 0; c < 128; c++) // lol see what I did there 
    {
        // load character glyph 
        if (FT_Load_Char(face, c, FT_LOAD_RENDER))
        {
            std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
            continue;
        }
        // generate texture
        unsigned int texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(
            GL_TEXTURE_2D,
            0,
            GL_RED,
            face->glyph->bitmap.width,
            face->glyph->bitmap.rows,
            0,
            GL_RED,
            GL_UNSIGNED_BYTE,
            face->glyph->bitmap.buffer
        );
        // set texture options
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 
        // now store character for later use
        Character character = {
            texture,
            glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
            glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
            face->glyph->advance.x
        };
        Characters.insert(std::pair<char, Character>(c, character));
    }
    glBindTexture(GL_TEXTURE_2D, 0);
    // destroy FreeType once we're finished
    FT_Done_Face(face);
    FT_Done_FreeType(ft);
}
 
void TextRenderer::RenderText(std::string text, float x, float y, float scale, glm::vec3 color)
{
    // activate corresponding render state  
    this->TextShader.Use();
    this->TextShader.SetVector3f("textColor", color);
    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(this->VAO);
 
    // iterate through all characters
    std::string::const_iterator c;
    for (c = text.begin(); c != text.end(); c++)
    {
        Character ch = Characters[*c];
 
        float xpos = x + ch.Bearing.x * scale;
        float ypos = y + (this->Characters['H'].Bearing.y - ch.Bearing.y) * scale;
 
        float w = ch.Size.x * scale;
        float h = ch.Size.y * scale;
        // update VBO for each character
        float vertices[6][4] = {
            { xpos,     ypos + h,   0.0f, 1.0f },
            { xpos + w, ypos,       1.0f, 0.0f },
            { xpos,     ypos,       0.0f, 0.0f },
 
            { xpos,     ypos + h,   0.0f, 1.0f },
            { xpos + w, ypos + h,   1.0f, 1.0f },
            { xpos + w, ypos,       1.0f, 0.0f }
        };
        // render glyph texture over quad
        glBindTexture(GL_TEXTURE_2D, ch.TextureID);
        // update content of VBO memory
        glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
        glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); // be sure to use glBufferSubData and not glBufferData
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        // render quad
        glDrawArrays(GL_TRIANGLES, 0, 6);
        // now advance cursors for next glyph
        x += (ch.Advance >> 6) * scale; // bitshift by 6 to get value in pixels (1/64th times 2^6 = 64)
    }
    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
}
Character.h:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#pragma once
#ifndef MYSTRUCT_H
#define MYSTRUCT_H
 
 
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
 
struct Character {
    unsigned int TextureID; // ID handle of the glyph texture
    glm::ivec2   Size;      // Size of glyph
    glm::ivec2   Bearing;   // Offset from baseline to left/top of glyph
    unsigned int Advance;   // Horizontal offset to advance to next glyph
};
 
#endif
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
14.10.2022, 23:34
Ответы с готовыми решениями:

Как использовать в js файле функцию из другого js файла?
Добрый день/вечер есть проблема. 2 js файла, в &quot;a.js&quot; есть функция &quot;create()&quot; и есть файл &quot;b.js&quot; там тоже функция...

Как использовать функцию из другого файла Python?
(Код будет ниже) У меня есть radiobutton, команда которая должна в ней исполниться находится в другом файле, как мне использовать...

Пытаюсь использовать статистическую функцию в предложении grup by, хоть это и нельзя.
Добавил в до того работающий запрос статистики поле так понимаю с неверно заданным условием сохранил выбило то что на скрине. Ошибка:...

3
Эксперт С++
 Аватар для hoggy
8973 / 4319 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
15.10.2022, 03:13
Цитата Сообщение от Teyllay Посмотреть сообщение
я пытаюсь импортировать код из другого файла cpp
Цитата Сообщение от Teyllay Посмотреть сообщение
как это исправить?
добавь в проект файл text_renderer.cpp

Добавлено через 8 секунд
Цитата Сообщение от Teyllay Посмотреть сообщение
я пытаюсь импортировать код из другого файла cpp
Цитата Сообщение от Teyllay Посмотреть сообщение
как это исправить?
добавь в проект файл text_renderer.cpp
0
0 / 0 / 0
Регистрация: 13.10.2022
Сообщений: 3
15.10.2022, 10:52  [ТС]
он и так добавлен
0
19500 / 10105 / 2461
Регистрация: 30.01.2014
Сообщений: 17,816
15.10.2022, 12:32
Teyllay, судя по сообщению о ошибке, у вас отсутствует определение функции Shader::Use.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
15.10.2022, 12:32
Помогаю со студенческими работами здесь

Не могу использовать функцию из другого класса через ->
Не понимаю,как нужно правильно это записать. Тут это работает: int Menu::FindName(List&lt;Smartphones&gt; lst) { ...

Каким образом использовать функцию другого класса
Начал изучать ООП С# и заблудился напрочь. Я создал класс: public class Gener { private const int...

Использовать класс из другого файла *.cs
Добрый день! У меня в проекте 3 класса, я хочу оставить в файле Form1.cs только логику GUI, а классы, которые делают расчеты вынести в...

Использовать класс из другого файла
Пишу веб апликацию. Нужен коннект к БД. Класс для БД хочу создать отдельно, потому что нужно в нескольких файлах его юзать. Но при...

Когда нужно использовать структуры, когда классы, а когда словарь?
Хеллоу. Не могу понять, когда, что, нужно использовать. Допустим мне нужно получить объект, который имеет список объектов. И...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru