• OpenGL_Learn15(投光物)


    1. 平行光

    1. cube.vs******************
    2. #version 330 core
    3. layout (location = 0) in vec3 aPos;
    4. layout (location =1 ) in vec3 aNormal;
    5. layout (location=2) in vec2 aTexCoords;
    6. out vec3 FragPos;
    7. out vec3 Normal;
    8. out vec2 TexCoords;
    9. uniform mat4 model;
    10. uniform mat4 view;
    11. uniform mat4 projection;
    12. void main()
    13. {
    14. FragPos=vec3(model*vec4(aPos,1.0));
    15. Normal=mat3(transpose(inverse(model)))*aNormal;
    16. TexCoords=aTexCoords;
    17. gl_Position = projection * view * vec4(FragPos, 1.0);
    18. }
    19. cube.fs******************
    20. #version 330 core
    21. out vec4 FragColor;
    22. in vec3 Normal;
    23. in vec3 FragPos;
    24. struct Material {
    25. sampler2D diffuse;
    26. sampler2D specular;
    27. float shininess;
    28. };
    29. in vec2 TexCoords;
    30. struct Light {
    31. vec3 direction;
    32. vec3 ambient;
    33. vec3 diffuse;
    34. vec3 specular;
    35. };
    36. uniform Material material;
    37. uniform Light light;
    38. uniform vec3 objectColor;
    39. uniform vec3 lightColor;
    40. uniform vec3 lightPos;
    41. uniform vec3 viewPos;
    42. void main()
    43. {
    44. //ambient
    45. vec3 ambient=vec3(0.1)*light.ambient*vec3(texture(material.diffuse,TexCoords));
    46. //diffuse
    47. vec3 norm=normalize(Normal);
    48. vec3 lightDir=normalize(-light.direction);//光的方向向量是光源位置向量与片段位置向量之间的向量差。
    49. //对norm和lightDir向量进行点乘,计算光源对当前片段实际的漫反射影响
    50. //两个向量之间的角度越大,漫反射分量就会越小,点乘的几何意义也如此
    51. float diff=max(dot(norm,lightDir),0.0);
    52. vec3 diffuse=light.diffuse*diff*vec3(texture(material.diffuse,TexCoords));
    53. //specular
    54. //漫反射是光源指向片段位置。现在这个是摄像机指向片段位置
    55. vec3 viewDir=normalize(viewPos-FragPos);
    56. vec3 reflectDir=reflect(-lightDir,norm);//reflect第一个参数就是要片段指向摄像机位置
    57. float spec=pow(max(dot(viewDir,reflectDir),0.0),material.shininess);
    58. vec3 specular=light.specular*spec*vec3(texture(material.specular,TexCoords));
    59. vec3 result=ambient+diffuse+specular;
    60. FragColor = vec4(result, 1.0);
    61. }
    62. light_cube.vs******************
    63. #version 330 core
    64. layout (location = 0) in vec3 aPos;
    65. uniform mat4 model;
    66. uniform mat4 view;
    67. uniform mat4 projection;
    68. void main()
    69. {
    70. gl_Position = projection * view * model * vec4(aPos, 1.0);
    71. }
    72. light_cube.fs******************
    73. #version 330 core
    74. out vec4 FragColor;
    75. uniform vec4 CubeFragColor;
    76. void main()
    77. {
    78. FragColor =vec4(1.0);
    79. }

    main.cpp

    1. #include
    2. #include
    3. #include
    4. #include "stb_image.h"
    5. #include
    6. #include "shader.h"
    7. #include "camera.h"
    8. #include
    9. #include
    10. #include
    11. void framebuffer_size_callback(GLFWwindow* window, int width, int height);
    12. void processInput(GLFWwindow* window);
    13. void mouse_callback(GLFWwindow* window, double xpos, double ypos);
    14. void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
    15. // settings
    16. const unsigned int SCR_WIDTH = 900;
    17. const unsigned int SCR_HEIGHT = 600;
    18. //camera
    19. Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
    20. float lastX = SCR_WIDTH / 2.0f;
    21. float lastY = SCR_HEIGHT / 2.0f;
    22. bool firstMouse = true;
    23. //timing
    24. float deltaTime = 0.0f;//不同配置绘制速度不同,所以需要这个属性
    25. float lastFrame = 0.0f;
    26. // utility function for loading a 2D texture from file
    27. // ---------------------------------------------------
    28. unsigned int loadTexture(char const* path)
    29. {
    30. unsigned int textureID;
    31. glGenTextures(1, &textureID);
    32. int width, height, nrComponents;
    33. unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0);
    34. if (data)
    35. {
    36. GLenum format;
    37. if (nrComponents == 1)
    38. format = GL_RED;
    39. else if (nrComponents == 3)
    40. format = GL_RGB;
    41. else if (nrComponents == 4)
    42. format = GL_RGBA;
    43. glBindTexture(GL_TEXTURE_2D, textureID);
    44. glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
    45. glGenerateMipmap(GL_TEXTURE_2D);
    46. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    47. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    48. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    49. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    50. stbi_image_free(data);
    51. }
    52. else
    53. {
    54. std::cout << "Texture failed to load at path: " << path << std::endl;
    55. stbi_image_free(data);
    56. }
    57. return textureID;
    58. }
    59. int main() {
    60. //glfw:initialize and configure
    61. //=============================
    62. glfwInit();
    63. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    64. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    65. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    66. #ifdef __APPLE__
    67. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    68. #endif
    69. //glfw window creation
    70. //=============================
    71. GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Learn", NULL, NULL);
    72. if (window == NULL) {
    73. std::cout << "Failed to create GLFW window" << std::endl;
    74. glfwTerminate();
    75. return -1;
    76. }
    77. glfwMakeContextCurrent(window);
    78. glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    79. glfwSetCursorPosCallback(window, mouse_callback);
    80. glfwSetScrollCallback(window, scroll_callback);
    81. //tell GLFW to capture our mouse
    82. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    83. //glad::load all OPenGL function pointers
    84. //=============================
    85. if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    86. std::cout << "Failed to initialize GLAD" << std::endl;
    87. return -1;
    88. }
    89. //configure gloabl opengl state
    90. //=============================
    91. glEnable(GL_DEPTH_TEST);
    92. //build and compile our shader zprogram
    93. //=============================
    94. Shader lightingShader("./cube.vs", "./cube.fs");
    95. Shader lightingCubeShader("./light_cube.vs", "./light_cube.fs");
    96. //set up vertex data
    97. float vertices[] = {
    98. // positions // normals // texture coords
    99. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
    100. 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
    101. 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
    102. 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
    103. -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
    104. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
    105. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
    106. 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
    107. 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    108. 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    109. -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
    110. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
    111. -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    112. -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
    113. -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    114. -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    115. -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
    116. -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    117. 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    118. 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
    119. 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    120. 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    121. 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
    122. 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    123. -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
    124. 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
    125. 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
    126. 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
    127. -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
    128. -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
    129. -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
    130. 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    131. 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
    132. 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
    133. -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
    134. -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
    135. };
    136. glm::vec3 cubePositions[] = {
    137. glm::vec3(0.0f, 0.0f, 0.0f),
    138. glm::vec3(2.0f, 5.0f, -15.0f),
    139. glm::vec3(-1.5f, -2.2f, -2.5f),
    140. glm::vec3(-3.8f, -2.0f, -12.3f),
    141. glm::vec3(2.4f, -0.4f, -3.5f),
    142. glm::vec3(-1.7f, 3.0f, -7.5f),
    143. glm::vec3(1.3f, -2.0f, -2.5f),
    144. glm::vec3(1.5f, 2.0f, -2.5f),
    145. glm::vec3(1.5f, 0.2f, -1.5f),
    146. glm::vec3(-1.3f, 1.0f, -1.5f)
    147. };
    148. //第一个
    149. unsigned int VBO, cubeVAO;
    150. glGenVertexArrays(1, &cubeVAO);
    151. glGenBuffers(1, &VBO);
    152. glBindBuffer(GL_ARRAY_BUFFER, VBO);
    153. glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    154. glBindVertexArray(cubeVAO);
    155. //position attribute
    156. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    157. glEnableVertexAttribArray(0);
    158. //normal attribute
    159. glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    160. glEnableVertexAttribArray(1);
    161. glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    162. glEnableVertexAttribArray(2);
    163. //第二个
    164. unsigned int lightCubeVAO;
    165. glGenVertexArrays(1, &lightCubeVAO);
    166. glBindVertexArray(lightCubeVAO);
    167. glBindBuffer(GL_ARRAY_BUFFER, VBO);
    168. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    169. glEnableVertexAttribArray(0);
    170. //----------
    171. std::string texturePath = "../../Data/container2.png";
    172. unsigned int diffuseMap = loadTexture(texturePath.c_str());
    173. std::string specularPath = "../../Data/container2_specular.png";
    174. unsigned int specularMap = loadTexture(specularPath.c_str());
    175. lightingShader.use();
    176. lightingShader.setInt("material.diffuse", 0);
    177. lightingShader.setInt("material.specular", 1);
    178. // render loop
    179. // -----------
    180. while (!glfwWindowShouldClose(window))
    181. {
    182. // per-frame time logic
    183. // --------------------
    184. float currentFrame = static_cast<float>(glfwGetTime());
    185. deltaTime = currentFrame - lastFrame;
    186. lastFrame = currentFrame;
    187. // input
    188. // -----
    189. processInput(window);
    190. // render
    191. // ------
    192. glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    193. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    194. // be sure to activate shader when setting uniforms/drawing objects
    195. lightingShader.use();
    196. lightingShader.setVec3("light.direction", -0.2f, -1.0f, -0.3f);
    197. lightingShader.setVec3("viewPos", camera.Position);
    198. //光照属性
    199. lightingShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
    200. lightingShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
    201. lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
    202. //材质属性
    203. lightingShader.setVec3("material.specular", 0.5f,0.5f, 0.5f);
    204. lightingShader.setFloat("material.shininess",32.0f);
    205. // view/projection transformations
    206. glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
    207. glm::mat4 view = camera.GetViewMatrix();
    208. lightingShader.setMat4("projection", projection);
    209. lightingShader.setMat4("view", view);
    210. // world transformation
    211. glm::mat4 model = glm::mat4(1.0f);
    212. lightingShader.setMat4("model", model);
    213. //bind diffuse map
    214. glActiveTexture(GL_TEXTURE0);
    215. glBindTexture(GL_TEXTURE_2D, diffuseMap);
    216. glActiveTexture(GL_TEXTURE1);
    217. glBindTexture(GL_TEXTURE_2D, specularMap);
    218. // render the cube
    219. glBindVertexArray(cubeVAO);
    220. for (unsigned int i = 0; i < 10; i++) {
    221. glm::mat4 model=glm::mat4(1.0f);
    222. model = glm::translate(model, cubePositions[i]);
    223. float angle = 20.0f * i;
    224. model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
    225. lightingShader.setMat4("model", model);
    226. glDrawArrays(GL_TRIANGLES, 0, 36);
    227. }
    228. // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
    229. // -------------------------------------------------------------------------------
    230. glfwSwapBuffers(window);
    231. glfwPollEvents();
    232. }
    233. glDeleteVertexArrays(1, &cubeVAO);
    234. glDeleteVertexArrays(1, &lightCubeVAO);
    235. glDeleteBuffers(1, &VBO);
    236. glfwTerminate();
    237. return 0;
    238. }
    239. void processInput(GLFWwindow* window)
    240. {
    241. if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
    242. glfwSetWindowShouldClose(window, true);
    243. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
    244. camera.ProcessKeyboard(FORWARD, deltaTime);
    245. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
    246. camera.ProcessKeyboard(BACKWARD, deltaTime);
    247. if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
    248. camera.ProcessKeyboard(LEFT, deltaTime);
    249. if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
    250. camera.ProcessKeyboard(RIGHT, deltaTime);
    251. }
    252. void framebuffer_size_callback(GLFWwindow* window, int width, int height)
    253. {
    254. // make sure the viewport matches the new window dimensions; note that width and
    255. // height will be significantly larger than specified on retina displays.
    256. glViewport(0, 0, width, height);
    257. }
    258. // glfw: whenever the mouse moves, this callback is called
    259. // -------------------------------------------------------
    260. void mouse_callback(GLFWwindow* window, double xposIn, double yposIn)
    261. {
    262. float xpos = static_cast<float>(xposIn);
    263. float ypos = static_cast<float>(yposIn);
    264. if (firstMouse)
    265. {
    266. lastX = xpos;
    267. lastY = ypos;
    268. firstMouse = false;
    269. }
    270. float xoffset = xpos - lastX;
    271. float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
    272. lastX = xpos;
    273. lastY = ypos;
    274. camera.ProcessMouseMovement(xoffset, yoffset);
    275. }
    276. // glfw: whenever the mouse scroll wheel scrolls, this callback is called
    277. // ----------------------------------------------------------------------
    278. void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
    279. {
    280. camera.ProcessMouseScroll(static_cast<float>(yoffset));
    281. }

    2. 点光源

    1. #version 330 core
    2. layout (location = 0) in vec3 aPos;
    3. layout (location =1 ) in vec3 aNormal;
    4. layout (location=2) in vec2 aTexCoords;
    5. out vec3 FragPos;
    6. out vec3 Normal;
    7. out vec2 TexCoords;
    8. uniform mat4 model;
    9. uniform mat4 view;
    10. uniform mat4 projection;
    11. void main()
    12. {
    13. FragPos=vec3(model*vec4(aPos,1.0));
    14. Normal=mat3(transpose(inverse(model)))*aNormal;
    15. TexCoords=aTexCoords;
    16. gl_Position = projection * view * vec4(FragPos, 1.0);
    17. }
    18. #version 330 core
    19. out vec4 FragColor;
    20. in vec3 Normal;
    21. in vec3 FragPos;
    22. struct Material {
    23. sampler2D diffuse;
    24. sampler2D specular;
    25. float shininess;
    26. };
    27. in vec2 TexCoords;
    28. struct Light {
    29. vec3 position;
    30. vec3 ambient;
    31. vec3 diffuse;
    32. vec3 specular;
    33. float constant;
    34. float linear;
    35. float quadratic;
    36. };
    37. uniform Material material;
    38. uniform Light light;
    39. uniform vec3 objectColor;
    40. uniform vec3 lightColor;
    41. uniform vec3 lightPos;
    42. uniform vec3 viewPos;
    43. void main()
    44. {
    45. float distance = length(light.position - FragPos);
    46. float attenuation = 1.0 / (light.constant + light.linear * distance +
    47. light.quadratic * (distance * distance));
    48. //ambient
    49. vec3 ambient=vec3(0.1)*light.ambient*vec3(texture(material.diffuse,TexCoords));
    50. //diffuse
    51. vec3 norm=normalize(Normal);
    52. vec3 lightDir=normalize(light.position-FragPos);//光的方向向量是光源位置向量与片段位置向量之间的向量差。
    53. //对norm和lightDir向量进行点乘,计算光源对当前片段实际的漫反射影响
    54. //两个向量之间的角度越大,漫反射分量就会越小,点乘的几何意义也如此
    55. float diff=max(dot(norm,lightDir),0.0);
    56. vec3 diffuse=light.diffuse*diff*vec3(texture(material.diffuse,TexCoords));
    57. //specular
    58. //漫反射是光源指向片段位置。现在这个是摄像机指向片段位置
    59. vec3 viewDir=normalize(viewPos-FragPos);
    60. vec3 reflectDir=reflect(-lightDir,norm);//reflect第一个参数就是要片段指向摄像机位置
    61. float spec=pow(max(dot(viewDir,reflectDir),0.0),material.shininess);
    62. vec3 specular=light.specular*spec*vec3(texture(material.specular,TexCoords));
    63. ambient*=attenuation;
    64. diffuse*=attenuation;
    65. specular*=attenuation;
    66. vec3 result=ambient+diffuse+specular;
    67. FragColor = vec4(result, 1.0);
    68. }
    69. #version 330 core
    70. layout (location = 0) in vec3 aPos;
    71. uniform mat4 model;
    72. uniform mat4 view;
    73. uniform mat4 projection;
    74. void main()
    75. {
    76. gl_Position = projection * view * model * vec4(aPos, 1.0);
    77. }
    78. #version 330 core
    79. out vec4 FragColor;
    80. void main()
    81. {
    82. FragColor =vec4(1.0);
    83. }

    camera.h

    1. #ifndef CAMERA_H
    2. #define CAMERA_H
    3. #include
    4. #include
    5. #include
    6. #include
    7. // Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
    8. enum Camera_Movement {
    9. FORWARD,
    10. BACKWARD,
    11. LEFT,
    12. RIGHT
    13. };
    14. // Default camera values
    15. const float YAW = -90.0f;
    16. const float PITCH = 0.0f;
    17. const float SPEED = 2.5f;
    18. const float SENSITIVITY = 0.1f;
    19. const float ZOOM = 45.0f;
    20. // An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL
    21. class Camera
    22. {
    23. public:
    24. // camera Attributes
    25. glm::vec3 Position;
    26. glm::vec3 Front;
    27. glm::vec3 Up;
    28. glm::vec3 Right;
    29. glm::vec3 WorldUp;
    30. // euler Angles
    31. float Yaw;
    32. float Pitch;
    33. // camera options
    34. float MovementSpeed;
    35. float MouseSensitivity;
    36. float Zoom;
    37. // constructor with vectors
    38. Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
    39. {
    40. Position = position;
    41. WorldUp = up;
    42. Yaw = yaw;
    43. Pitch = pitch;
    44. updateCameraVectors();
    45. }
    46. // constructor with scalar values
    47. Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
    48. {
    49. Position = glm::vec3(posX, posY, posZ);
    50. WorldUp = glm::vec3(upX, upY, upZ);
    51. Yaw = yaw;
    52. Pitch = pitch;
    53. updateCameraVectors();
    54. }
    55. // returns the view matrix calculated using Euler Angles and the LookAt Matrix
    56. glm::mat4 GetViewMatrix()
    57. {
    58. return glm::lookAt(Position, Position + Front, Up);
    59. }
    60. // processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
    61. void ProcessKeyboard(Camera_Movement direction, float deltaTime)
    62. {
    63. float velocity = MovementSpeed * deltaTime;
    64. if (direction == FORWARD)
    65. Position += Front * velocity;
    66. if (direction == BACKWARD)
    67. Position -= Front * velocity;
    68. if (direction == LEFT)
    69. Position -= Right * velocity;
    70. if (direction == RIGHT)
    71. Position += Right * velocity;
    72. }
    73. // processes input received from a mouse input system. Expects the offset value in both the x and y direction.
    74. void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true)
    75. {
    76. xoffset *= MouseSensitivity;
    77. yoffset *= MouseSensitivity;
    78. Yaw += xoffset;
    79. Pitch += yoffset;
    80. // make sure that when pitch is out of bounds, screen doesn't get flipped
    81. if (constrainPitch)
    82. {
    83. if (Pitch > 89.0f)
    84. Pitch = 89.0f;
    85. if (Pitch < -89.0f)
    86. Pitch = -89.0f;
    87. }
    88. // update Front, Right and Up Vectors using the updated Euler angles
    89. updateCameraVectors();
    90. }
    91. // processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
    92. void ProcessMouseScroll(float yoffset)
    93. {
    94. Zoom -= (float)yoffset;
    95. if (Zoom < 1.0f)
    96. Zoom = 1.0f;
    97. if (Zoom > 45.0f)
    98. Zoom = 45.0f;
    99. }
    100. private:
    101. // calculates the front vector from the Camera's (updated) Euler Angles
    102. void updateCameraVectors()
    103. {
    104. // calculate the new Front vector
    105. glm::vec3 front;
    106. front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
    107. front.y = sin(glm::radians(Pitch));
    108. front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
    109. Front = glm::normalize(front);
    110. // also re-calculate the Right and Up vector
    111. Right = glm::normalize(glm::cross(Front, WorldUp)); // normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
    112. Up = glm::normalize(glm::cross(Right, Front));
    113. }
    114. };
    115. #endif

    main.cpp

    1. #include
    2. #include
    3. #include
    4. #include "stb_image.h"
    5. #include
    6. #include "shader.h"
    7. #include "camera.h"
    8. #include
    9. #include
    10. #include
    11. void framebuffer_size_callback(GLFWwindow* window, int width, int height);
    12. void processInput(GLFWwindow* window);
    13. void mouse_callback(GLFWwindow* window, double xpos, double ypos);
    14. void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
    15. unsigned int loadTexture(char const* path);
    16. // settings
    17. const unsigned int SCR_WIDTH = 900;
    18. const unsigned int SCR_HEIGHT = 600;
    19. //camera
    20. Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
    21. float lastX = SCR_WIDTH / 2.0f;
    22. float lastY = SCR_HEIGHT / 2.0f;
    23. bool firstMouse = true;
    24. //timing
    25. float deltaTime = 0.0f;//不同配置绘制速度不同,所以需要这个属性
    26. float lastFrame = 0.0f;
    27. // lighting
    28. glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
    29. int main() {
    30. //glfw:initialize and configure
    31. //=============================
    32. glfwInit();
    33. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    34. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    35. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    36. #ifdef __APPLE__
    37. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    38. #endif
    39. //glfw window creation
    40. //=============================
    41. GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Learn", NULL, NULL);
    42. if (window == NULL) {
    43. std::cout << "Failed to create GLFW window" << std::endl;
    44. glfwTerminate();
    45. return -1;
    46. }
    47. glfwMakeContextCurrent(window);
    48. glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    49. glfwSetCursorPosCallback(window, mouse_callback);
    50. glfwSetScrollCallback(window, scroll_callback);
    51. //tell GLFW to capture our mouse
    52. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    53. //glad::load all OPenGL function pointers
    54. //=============================
    55. if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    56. std::cout << "Failed to initialize GLAD" << std::endl;
    57. return -1;
    58. }
    59. //configure gloabl opengl state
    60. //=============================
    61. glEnable(GL_DEPTH_TEST);
    62. //build and compile our shader zprogram
    63. //=============================
    64. Shader lightingShader("./cube.vs", "./cube.fs");
    65. Shader lightingCubeShader("./light_cube.vs", "./light_cube.fs");
    66. //set up vertex data
    67. float vertices[] = {
    68. // positions // normals // texture coords
    69. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
    70. 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
    71. 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
    72. 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
    73. -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
    74. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
    75. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
    76. 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
    77. 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    78. 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    79. -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
    80. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
    81. -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    82. -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
    83. -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    84. -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    85. -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
    86. -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    87. 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    88. 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
    89. 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    90. 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    91. 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
    92. 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    93. -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
    94. 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
    95. 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
    96. 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
    97. -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
    98. -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
    99. -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
    100. 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    101. 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
    102. 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
    103. -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
    104. -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
    105. };
    106. glm::vec3 cubePositions[] = {
    107. glm::vec3(0.0f, 0.0f, 0.0f),
    108. glm::vec3(2.0f, 5.0f, -15.0f),
    109. glm::vec3(-1.5f, -2.2f, -2.5f),
    110. glm::vec3(-3.8f, -2.0f, -12.3f),
    111. glm::vec3(2.4f, -0.4f, -3.5f),
    112. glm::vec3(-1.7f, 3.0f, -7.5f),
    113. glm::vec3(1.3f, -2.0f, -2.5f),
    114. glm::vec3(1.5f, 2.0f, -2.5f),
    115. glm::vec3(1.5f, 0.2f, -1.5f),
    116. glm::vec3(-1.3f, 1.0f, -1.5f)
    117. };
    118. //第一个
    119. unsigned int VBO, cubeVAO;
    120. glGenVertexArrays(1, &cubeVAO);
    121. glGenBuffers(1, &VBO);
    122. glBindBuffer(GL_ARRAY_BUFFER, VBO);
    123. glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    124. glBindVertexArray(cubeVAO);
    125. //position attribute
    126. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    127. glEnableVertexAttribArray(0);
    128. //normal attribute
    129. glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    130. glEnableVertexAttribArray(1);
    131. glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    132. glEnableVertexAttribArray(2);
    133. //第二个
    134. unsigned int lightCubeVAO;
    135. glGenVertexArrays(1, &lightCubeVAO);
    136. glBindVertexArray(lightCubeVAO);
    137. glBindBuffer(GL_ARRAY_BUFFER, VBO);
    138. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    139. glEnableVertexAttribArray(0);
    140. //----------
    141. std::string texturePath = "../../Data/container2.png";
    142. unsigned int diffuseMap = loadTexture(texturePath.c_str());
    143. std::string specularPath = "../../Data/container2_specular.png";
    144. unsigned int specularMap = loadTexture(specularPath.c_str());
    145. lightingShader.use();
    146. lightingShader.setInt("material.diffuse", 0);
    147. lightingShader.setInt("material.specular", 1);
    148. // render loop
    149. // -----------
    150. while (!glfwWindowShouldClose(window))
    151. {
    152. // per-frame time logic
    153. // --------------------
    154. float currentFrame = static_cast<float>(glfwGetTime());
    155. deltaTime = currentFrame - lastFrame;
    156. lastFrame = currentFrame;
    157. // input
    158. // -----
    159. processInput(window);
    160. // render
    161. // ------
    162. glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    163. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    164. // be sure to activate shader when setting uniforms/drawing objects
    165. lightingShader.use();
    166. lightingShader.setVec3("light.position",lightPos);
    167. lightingShader.setVec3("viewPos", camera.Position);
    168. //光照属性
    169. lightingShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
    170. lightingShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
    171. lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
    172. lightingShader.setFloat("light.constant", 1.0f);
    173. lightingShader.setFloat("light.linear", 0.09f);
    174. lightingShader.setFloat("light.quadratic", 0.032f);
    175. //材质属性
    176. lightingShader.setVec3("material.specular", 0.5f,0.5f, 0.5f);
    177. lightingShader.setFloat("material.shininess",32.0f);
    178. // view/projection transformations
    179. glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
    180. glm::mat4 view = camera.GetViewMatrix();
    181. lightingShader.setMat4("projection", projection);
    182. lightingShader.setMat4("view", view);
    183. // world transformation
    184. glm::mat4 model = glm::mat4(1.0f);
    185. lightingShader.setMat4("model", model);
    186. //bind diffuse map
    187. glActiveTexture(GL_TEXTURE0);
    188. glBindTexture(GL_TEXTURE_2D, diffuseMap);
    189. glActiveTexture(GL_TEXTURE1);
    190. glBindTexture(GL_TEXTURE_2D, specularMap);
    191. // render the cube
    192. glBindVertexArray(cubeVAO);
    193. for (unsigned int i = 0; i < 10; i++) {
    194. glm::mat4 model=glm::mat4(1.0f);
    195. model = glm::translate(model, cubePositions[i]);
    196. float angle = 20.0f * i;
    197. model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
    198. lightingShader.setMat4("model", model);
    199. glDrawArrays(GL_TRIANGLES, 0, 36);
    200. }
    201. // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
    202. // -------------------------------------------------------------------------------
    203. glfwSwapBuffers(window);
    204. glfwPollEvents();
    205. }
    206. glDeleteVertexArrays(1, &cubeVAO);
    207. glDeleteVertexArrays(1, &lightCubeVAO);
    208. glDeleteBuffers(1, &VBO);
    209. glfwTerminate();
    210. return 0;
    211. }
    212. void processInput(GLFWwindow* window)
    213. {
    214. if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
    215. glfwSetWindowShouldClose(window, true);
    216. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
    217. camera.ProcessKeyboard(FORWARD, deltaTime);
    218. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
    219. camera.ProcessKeyboard(BACKWARD, deltaTime);
    220. if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
    221. camera.ProcessKeyboard(LEFT, deltaTime);
    222. if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
    223. camera.ProcessKeyboard(RIGHT, deltaTime);
    224. }
    225. void framebuffer_size_callback(GLFWwindow* window, int width, int height)
    226. {
    227. // make sure the viewport matches the new window dimensions; note that width and
    228. // height will be significantly larger than specified on retina displays.
    229. glViewport(0, 0, width, height);
    230. }
    231. // glfw: whenever the mouse moves, this callback is called
    232. // -------------------------------------------------------
    233. void mouse_callback(GLFWwindow* window, double xposIn, double yposIn)
    234. {
    235. float xpos = static_cast<float>(xposIn);
    236. float ypos = static_cast<float>(yposIn);
    237. if (firstMouse)
    238. {
    239. lastX = xpos;
    240. lastY = ypos;
    241. firstMouse = false;
    242. }
    243. float xoffset = xpos - lastX;
    244. float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
    245. lastX = xpos;
    246. lastY = ypos;
    247. camera.ProcessMouseMovement(xoffset, yoffset);
    248. }
    249. // glfw: whenever the mouse scroll wheel scrolls, this callback is called
    250. // ----------------------------------------------------------------------
    251. void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
    252. {
    253. camera.ProcessMouseScroll(static_cast<float>(yoffset));
    254. }
    255. // utility function for loading a 2D texture from file
    256. // ---------------------------------------------------
    257. unsigned int loadTexture(char const* path)
    258. {
    259. unsigned int textureID;
    260. glGenTextures(1, &textureID);
    261. int width, height, nrComponents;
    262. unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0);
    263. if (data)
    264. {
    265. GLenum format;
    266. if (nrComponents == 1)
    267. format = GL_RED;
    268. else if (nrComponents == 3)
    269. format = GL_RGB;
    270. else if (nrComponents == 4)
    271. format = GL_RGBA;
    272. glBindTexture(GL_TEXTURE_2D, textureID);
    273. glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
    274. glGenerateMipmap(GL_TEXTURE_2D);
    275. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    276. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    277. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    278. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    279. stbi_image_free(data);
    280. }
    281. else
    282. {
    283. std::cout << "Texture failed to load at path: " << path << std::endl;
    284. stbi_image_free(data);
    285. }
    286. return textureID;
    287. }

     

    3. 手电筒

    1. #version 330 core
    2. layout (location = 0) in vec3 aPos;
    3. uniform mat4 model;
    4. uniform mat4 view;
    5. uniform mat4 projection;
    6. void main()
    7. {
    8. gl_Position = projection * view * model * vec4(aPos, 1.0);
    9. }
    10. #version 330 core
    11. out vec4 FragColor;
    12. void main()
    13. {
    14. FragColor =vec4(1.0);
    15. }
    16. #version 330 core
    17. layout (location = 0) in vec3 aPos;
    18. layout (location =1 ) in vec3 aNormal;
    19. layout (location=2) in vec2 aTexCoords;
    20. out vec3 FragPos;
    21. out vec3 Normal;
    22. out vec2 TexCoords;
    23. uniform mat4 model;
    24. uniform mat4 view;
    25. uniform mat4 projection;
    26. void main()
    27. {
    28. FragPos=vec3(model*vec4(aPos,1.0));
    29. Normal=mat3(transpose(inverse(model)))*aNormal;
    30. TexCoords=aTexCoords;
    31. gl_Position = projection * view * vec4(FragPos, 1.0);
    32. }
    33. #version 330 core
    34. out vec4 FragColor;
    35. in vec3 Normal;
    36. in vec3 FragPos;
    37. struct Material {
    38. sampler2D diffuse;
    39. sampler2D specular;
    40. float shininess;
    41. };
    42. in vec2 TexCoords;
    43. struct Light {
    44. vec3 position;
    45. vec3 direction;
    46. float cutOff;
    47. float outerCutOff;
    48. vec3 ambient;
    49. vec3 diffuse;
    50. vec3 specular;
    51. float constant;
    52. float linear;
    53. float quadratic;
    54. };
    55. uniform Material material;
    56. uniform Light light;
    57. uniform vec3 objectColor;
    58. uniform vec3 lightColor;
    59. uniform vec3 lightPos;
    60. uniform vec3 viewPos;
    61. void main()
    62. {
    63. vec3 lightDir=normalize(light.position-FragPos);
    64. //判断
    65. float theta=dot(lightDir,normalize(-light.direction));
    66. if(theta > light.cutOff) // remember that we're working with angles as cosines instead of degrees so a '>' is used.
    67. {
    68. // ambient
    69. vec3 ambient = light.ambient * texture(material.diffuse, TexCoords).rgb;
    70. // diffuse
    71. vec3 norm = normalize(Normal);
    72. float diff = max(dot(norm, lightDir), 0.0);
    73. vec3 diffuse = light.diffuse * diff * texture(material.diffuse, TexCoords).rgb;
    74. // specular
    75. vec3 viewDir = normalize(viewPos - FragPos);
    76. vec3 reflectDir = reflect(-lightDir, norm);
    77. float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    78. vec3 specular = light.specular * spec * texture(material.specular, TexCoords).rgb;
    79. // attenuation
    80. float distance = length(light.position - FragPos);
    81. float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
    82. // ambient *= attenuation; // remove attenuation from ambient, as otherwise at large distances the light would be darker inside than outside the spotlight due the ambient term in the else branch
    83. diffuse *= attenuation;
    84. specular *= attenuation;
    85. vec3 result = ambient + diffuse + specular;
    86. FragColor = vec4(result, 1.0);
    87. }
    88. else
    89. {
    90. // else, use ambient light so scene isn't completely dark outside the spotlight.
    91. FragColor = vec4(light.ambient * texture(material.diffuse, TexCoords).rgb, 1.0);
    92. }
    93. }

    main.cpp

    1. #include
    2. #include
    3. #include
    4. #include "stb_image.h"
    5. #include
    6. #include "shader.h"
    7. #include "camera.h"
    8. #include
    9. #include
    10. #include
    11. void framebuffer_size_callback(GLFWwindow* window, int width, int height);
    12. void processInput(GLFWwindow* window);
    13. void mouse_callback(GLFWwindow* window, double xpos, double ypos);
    14. void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
    15. unsigned int loadTexture(char const* path);
    16. // settings
    17. const unsigned int SCR_WIDTH = 900;
    18. const unsigned int SCR_HEIGHT = 600;
    19. //camera
    20. Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
    21. float lastX = SCR_WIDTH / 2.0f;
    22. float lastY = SCR_HEIGHT / 2.0f;
    23. bool firstMouse = true;
    24. //timing
    25. float deltaTime = 0.0f;//不同配置绘制速度不同,所以需要这个属性
    26. float lastFrame = 0.0f;
    27. // lighting
    28. glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
    29. int main() {
    30. //glfw:initialize and configure
    31. //=============================
    32. glfwInit();
    33. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    34. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    35. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    36. #ifdef __APPLE__
    37. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    38. #endif
    39. //glfw window creation
    40. //=============================
    41. GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Learn", NULL, NULL);
    42. if (window == NULL) {
    43. std::cout << "Failed to create GLFW window" << std::endl;
    44. glfwTerminate();
    45. return -1;
    46. }
    47. glfwMakeContextCurrent(window);
    48. glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    49. glfwSetCursorPosCallback(window, mouse_callback);
    50. glfwSetScrollCallback(window, scroll_callback);
    51. //tell GLFW to capture our mouse
    52. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    53. //glad::load all OPenGL function pointers
    54. //=============================
    55. if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    56. std::cout << "Failed to initialize GLAD" << std::endl;
    57. return -1;
    58. }
    59. //configure gloabl opengl state
    60. //=============================
    61. glEnable(GL_DEPTH_TEST);
    62. //build and compile our shader zprogram
    63. //=============================
    64. Shader lightingShader("./cube.vs", "./cube.fs");
    65. Shader lightingCubeShader("./light_cube.vs", "./light_cube.fs");
    66. //set up vertex data
    67. float vertices[] = {
    68. // positions // normals // texture coords
    69. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
    70. 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
    71. 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
    72. 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
    73. -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
    74. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
    75. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
    76. 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
    77. 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    78. 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    79. -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
    80. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
    81. -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    82. -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
    83. -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    84. -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    85. -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
    86. -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    87. 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    88. 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
    89. 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    90. 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
    91. 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
    92. 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
    93. -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
    94. 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
    95. 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
    96. 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
    97. -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
    98. -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
    99. -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
    100. 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    101. 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
    102. 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
    103. -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
    104. -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
    105. };
    106. glm::vec3 cubePositions[] = {
    107. glm::vec3(0.0f, 0.0f, 0.0f),
    108. glm::vec3(2.0f, 5.0f, -15.0f),
    109. glm::vec3(-1.5f, -2.2f, -2.5f),
    110. glm::vec3(-3.8f, -2.0f, -12.3f),
    111. glm::vec3(2.4f, -0.4f, -3.5f),
    112. glm::vec3(-1.7f, 3.0f, -7.5f),
    113. glm::vec3(1.3f, -2.0f, -2.5f),
    114. glm::vec3(1.5f, 2.0f, -2.5f),
    115. glm::vec3(1.5f, 0.2f, -1.5f),
    116. glm::vec3(-1.3f, 1.0f, -1.5f)
    117. };
    118. //第一个
    119. unsigned int VBO, cubeVAO;
    120. glGenVertexArrays(1, &cubeVAO);
    121. glGenBuffers(1, &VBO);
    122. glBindBuffer(GL_ARRAY_BUFFER, VBO);
    123. glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    124. glBindVertexArray(cubeVAO);
    125. //position attribute
    126. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    127. glEnableVertexAttribArray(0);
    128. //normal attribute
    129. glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    130. glEnableVertexAttribArray(1);
    131. glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    132. glEnableVertexAttribArray(2);
    133. //第二个
    134. unsigned int lightCubeVAO;
    135. glGenVertexArrays(1, &lightCubeVAO);
    136. glBindVertexArray(lightCubeVAO);
    137. glBindBuffer(GL_ARRAY_BUFFER, VBO);
    138. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    139. glEnableVertexAttribArray(0);
    140. //----------
    141. std::string texturePath = "../../Data/container2.png";
    142. unsigned int diffuseMap = loadTexture(texturePath.c_str());
    143. std::string specularPath = "../../Data/container2_specular.png";
    144. unsigned int specularMap = loadTexture(specularPath.c_str());
    145. lightingShader.use();
    146. lightingShader.setInt("material.diffuse", 0);
    147. lightingShader.setInt("material.specular", 1);
    148. // render loop
    149. // -----------
    150. while (!glfwWindowShouldClose(window))
    151. {
    152. // per-frame time logic
    153. // --------------------
    154. float currentFrame = static_cast<float>(glfwGetTime());
    155. deltaTime = currentFrame - lastFrame;
    156. lastFrame = currentFrame;
    157. // input
    158. // -----
    159. processInput(window);
    160. // render
    161. // ------
    162. glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    163. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    164. // be sure to activate shader when setting uniforms/drawing objects
    165. lightingShader.use();
    166. lightingShader.setVec3("light.position", camera.Position);
    167. lightingShader.setVec3("light.direction", camera.Front);
    168. lightingShader.setFloat("light.cutOff", glm::cos(glm::radians(12.5f)));
    169. lightingShader.setVec3("viewPos", camera.Position);
    170. //光照属性
    171. lightingShader.setVec3("light.ambient", 0.1f, 0.1f, 0.1f);
    172. lightingShader.setVec3("light.diffuse", 0.8f, 0.8f, 0.8f);
    173. lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
    174. lightingShader.setFloat("light.constant", 1.0f);
    175. lightingShader.setFloat("light.linear", 0.09f);
    176. lightingShader.setFloat("light.quadratic", 0.032f);
    177. //材质属性
    178. lightingShader.setFloat("material.shininess", 32.0f);
    179. // view/projection transformations
    180. glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
    181. glm::mat4 view = camera.GetViewMatrix();
    182. lightingShader.setMat4("projection", projection);
    183. lightingShader.setMat4("view", view);
    184. // world transformation
    185. glm::mat4 model = glm::mat4(1.0f);
    186. lightingShader.setMat4("model", model);
    187. //bind diffuse map
    188. glActiveTexture(GL_TEXTURE0);
    189. glBindTexture(GL_TEXTURE_2D, diffuseMap);
    190. glActiveTexture(GL_TEXTURE1);
    191. glBindTexture(GL_TEXTURE_2D, specularMap);
    192. // render the cube
    193. glBindVertexArray(cubeVAO);
    194. for (unsigned int i = 0; i < 10; i++) {
    195. glm::mat4 model = glm::mat4(1.0f);
    196. model = glm::translate(model, cubePositions[i]);
    197. float angle = 20.0f * i;
    198. model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
    199. lightingShader.setMat4("model", model);
    200. glDrawArrays(GL_TRIANGLES, 0, 36);
    201. }
    202. // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
    203. // -------------------------------------------------------------------------------
    204. glfwSwapBuffers(window);
    205. glfwPollEvents();
    206. }
    207. glDeleteVertexArrays(1, &cubeVAO);
    208. glDeleteVertexArrays(1, &lightCubeVAO);
    209. glDeleteBuffers(1, &VBO);
    210. glfwTerminate();
    211. return 0;
    212. }
    213. void processInput(GLFWwindow* window)
    214. {
    215. if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
    216. glfwSetWindowShouldClose(window, true);
    217. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
    218. camera.ProcessKeyboard(FORWARD, deltaTime);
    219. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
    220. camera.ProcessKeyboard(BACKWARD, deltaTime);
    221. if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
    222. camera.ProcessKeyboard(LEFT, deltaTime);
    223. if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
    224. camera.ProcessKeyboard(RIGHT, deltaTime);
    225. }
    226. void framebuffer_size_callback(GLFWwindow* window, int width, int height)
    227. {
    228. // make sure the viewport matches the new window dimensions; note that width and
    229. // height will be significantly larger than specified on retina displays.
    230. glViewport(0, 0, width, height);
    231. }
    232. // glfw: whenever the mouse moves, this callback is called
    233. // -------------------------------------------------------
    234. void mouse_callback(GLFWwindow* window, double xposIn, double yposIn)
    235. {
    236. float xpos = static_cast<float>(xposIn);
    237. float ypos = static_cast<float>(yposIn);
    238. if (firstMouse)
    239. {
    240. lastX = xpos;
    241. lastY = ypos;
    242. firstMouse = false;
    243. }
    244. float xoffset = xpos - lastX;
    245. float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
    246. lastX = xpos;
    247. lastY = ypos;
    248. camera.ProcessMouseMovement(xoffset, yoffset);
    249. }
    250. // glfw: whenever the mouse scroll wheel scrolls, this callback is called
    251. // ----------------------------------------------------------------------
    252. void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
    253. {
    254. camera.ProcessMouseScroll(static_cast<float>(yoffset));
    255. }
    256. // utility function for loading a 2D texture from file
    257. // ---------------------------------------------------
    258. unsigned int loadTexture(char const* path)
    259. {
    260. unsigned int textureID;
    261. glGenTextures(1, &textureID);
    262. int width, height, nrComponents;
    263. unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0);
    264. if (data)
    265. {
    266. GLenum format;
    267. if (nrComponents == 1)
    268. format = GL_RED;
    269. else if (nrComponents == 3)
    270. format = GL_RGB;
    271. else if (nrComponents == 4)
    272. format = GL_RGBA;
    273. glBindTexture(GL_TEXTURE_2D, textureID);
    274. glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
    275. glGenerateMipmap(GL_TEXTURE_2D);
    276. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    277. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    278. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    279. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    280. stbi_image_free(data);
    281. }
    282. else
    283. {
    284. std::cout << "Texture failed to load at path: " << path << std::endl;
    285. stbi_image_free(data);
    286. }
    287. return textureID;
    288. }

     

  • 相关阅读:
    花好月圆│以代码寄相思,绘嫦娥之奔月
    智能网卡的网络加速技术
    MySQL安装、修改默认字符集、添加path路径 (超详细,带图文)
    PDF如何解密?介绍几个简单小方法
    【bioinfo】sam文件可选区域字段(Optional Feild)含义
    大模型分布式训练并行技术(六)-多维混合并行
    电脑win11怎么还原系统?分享5种电脑系统还原的方法
    Golang RabbitMQ实现的延时队列
    Layui数据表格table排序(后端PHP)
    PIE-Engine 教程:水稻面积提取2—监督分类(宿迁市)
  • 原文地址:https://blog.csdn.net/qq_59068750/article/details/134503307