Can't assign C++ array - c++

Context: Need to set verts in TestTextures3SpriteObj s1 to the verts1 array. Gives me an error "expression must be modifiable lvalue". After its copied the vertices will be sent to the GPU as buffer data with OpenGL and GLUT.
Only relevant excerpts of code included
#pragma once
class TestTextures3SpriteObj
{
public:
int spriteid;
int vao;
int texid;
float verts[];
};
const float verts1[] = { 0.5 ,0.5, 0.0, 0.9, 0.5, 0.3, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.3, 0.3, 0.9, 1.0, 1.0, 1.0,
-0.5, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0,
-0.5, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
TestTextures3SpriteObj s1;
s1.verts = verts1;

Actually you are not accessing the variable ...
if you want access individual element, use index
s1.verts1[0]
If you want to copy use std::copy
std::copy(verts1, verts1 + 36, s1.verts);

#include <iostream>
using namespace std;
class TestTextures3SpriteObj
{
public:
int spriteid;
int vao;
int texid;
float verts[36]; //assign the size to the array
};
const float verts1[] = { 0.5 ,0.5, 0.0, 0.9, 0.5, 0.3, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.3, 0.3, 0.9, 1.0, 1.0, 1.0,
-0.5, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0,
-0.5, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
int main()
{
TestTextures3SpriteObj s1;
int len=sizeof(verts1)/sizeof(verts1[0]);
//copies the entire array to the object with member verts
std::copy(verts1, verts1 + 36, s1.verts);
//printing the values in the s1 object
for(int i=0;i<len;i++)
{
cout<<s1.verts[i]<<" ";
}
}
Assign a size to the array in the class and then later perform the std::copy to copy the values in the verts array.

Related

Calculate Normals in Shader

I am new to OpenGL and Shaders.
I want to write a toon shader.
I have this OpenGL code:
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
float black[] = { 0.0, 0.0, 0.0, 1.0 };
float red[] = { 1.0, 0.0, 0.0, 1.0 };
float green[] = { 0.0, 1.0, 0.0, 1.0 };
float blue[] = { 0.0, 0.0, 1.0, 1.0 };
float white[] = { 1.0, 1.0, 1.0, 1.0 };
float lowAmbient[] = { 0.2, 0.2, 0.2, 1.0 };
float fullAmbient[] = { 1.0, 1.0, 1.0, 1.0 };
glMaterialfv(GL_FRONT, GL_AMBIENT, blue);
glMaterialfv(GL_FRONT, GL_DIFFUSE, blue);
glMaterialfv(GL_FRONT, GL_SPECULAR, white);
glMaterialf(GL_FRONT, GL_SHININESS, 128.0);
glLightfv(GL_LIGHT0, GL_AMBIENT, lowAmbient);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -9);
glRotatef(45, 1, 0, 0);
glRotatef(45, 0, 0, 1);
glBegin(GL_QUADS);
//front
glNormal3f(0.0, 0.0, -1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
//back
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, 1.0, -1.0);
//right
glNormal3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(1.0, 1.0, -1.0);
//left
glNormal3f(-1.0, 0.0, 0.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(-1.0, 1.0, 1.0);
//top
glNormal3f(0.0, 1.0, 0.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, -1.0);
//bottom
glNormal3f(0.0, -1.0, 0.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, -1.0);
glEnd();
//Swap back and front buffer
glutSwapBuffers();
}
void init()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glEnable(GL_DEPTH_TEST);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
float ambientLight[] = { 0.2,0.2,0.2,1.0 };
float diffuseLight[] = { 0.8,0.8,0.8,1.0 };
float specularLight[] = { 1.0,1.0,1.0,1.0 };
float lightPosition[] = { 0.5,0.5,0.0,1.0 };
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
}
My Shader Codes:
#shader vertex
#version 330 core
void main()
{
}
#shader fragment
#version 330 core
vec3 LightPosition = gl_LightSource[0].position;//I don't know this is true or not
vec3 Normal;//I don't know how to calculate
void main()
{
vec4 color1 = gl_FrontMaterial.diffuse + gl_FrontMaterial.specular +
gl_FrontMaterial.ambient;
vec4 color2;
float intensity = dot(LightPosition, Normal);
if (intensity > 0.95) color2 = vec4(1.0, 1.0, 1.0, 1.0);
else if (intensity > 0.75) color2 = vec4(0.8, 0.8, 0.8, 1.0);
else if (intensity > 0.50) color2 = vec4(0.6, 0.6, 0.6, 1.0);
else if (intensity > 0.25) color2 = vec4(0.4, 0.4, 0.4, 1.0);
else color2 = vec4(0.2, 0.2, 0.2, 1.0);
gl_FragColor = color1 * color2;
}
To calculate light intensity and apply colors to my cube object I should know normals.
How can I calculate, or if there is a way, reach them?
(I have no problem with the shader compilation, or other OpenGL stuff. If I close my shader compilation lines I can see a green cube.)

GLFW-RS only shows black square instead of rotating cubes

I am trying to reformat C++ code I created from learnopengl.com with Rust bindings and it isn't quite working as expected. I am only getting a black square when I should be getting 10 rotating textured cubes.
Here's an image of my output window whenever I run the application.
Could somebody help me figure out what's going wrong? I can't understand it and it's driving me up the walls.
The code is quite lengthy so here is link to the repository if that makes it easier to read. Github GLFW Repo
main.rs
extern crate gl;
extern crate glfw;
extern crate glm;
extern crate image;
mod shader;
// use glfw::ffi;
use gl::types::*;
use glfw::{Action, Context, Key};
use glm::*;
use std::ffi::c_void;
use std::mem::size_of;
use shader::shader::Shader;
fn main() {
let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
glfw.window_hint(glfw::WindowHint::ContextVersion(4, 3));
glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));
glfw.window_hint(glfw::WindowHint::OpenGlProfile(
glfw::OpenGlProfileHint::Core,
));
let (mut window, events) = glfw
.create_window(800, 600, "Hello this is window", glfw::WindowMode::Windowed)
.expect("Failed to create GLFW window.");
window.set_title("OpenGL Custom App");
window.set_key_polling(true);
window.make_current();
window.set_framebuffer_size_polling(true);
load_gl_functions(&mut window);
// ffi::glfwSetWindowSizeCallback(*window, cbfun: Option<GLFWwindowsizefun>);
// First three verticies, last two texture
let _vertices: [f32; 180] = [
-0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5,
-0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5,
0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5,
0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5,
1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0,
0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5,
-0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5,
1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5,
-0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0,
];
let cube_positions: [Vec3; 10] = [
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(2.0, 5.0, -15.0),
glm::vec3(-1.5, -2.2, -2.5),
glm::vec3(-3.8, -2.0, -12.3),
glm::vec3(2.4, -0.4, -3.5),
glm::vec3(-1.7, 3.0, -7.5),
glm::vec3(1.3, -2.0, -2.5),
glm::vec3(1.5, 2.0, -2.5),
glm::vec3(1.5, 0.2, -1.5),
glm::vec3(-1.3, 1.0, -1.5),
];
let mut vbo: GLuint = 0;
let mut vao: GLuint = 0;
let mut texture1: u32 = 0;
let mut texture2: u32 = 0;
let shader = Shader::create_shader(
"src/shaders/vertShader.vert",
"src/shaders/fragShader.frag",
&mut window,
)
.expect("There was an error creating the program.");
unsafe {
gl::Enable(gl::DEPTH_TEST);
// Vertices pointer
gl::GenBuffers(1, &mut vbo);
gl::GenVertexArrays(1, &mut vao);
gl::BindVertexArray(vao);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(
gl::ARRAY_BUFFER,
size_of::<[f32; 180]>() as isize,
_vertices.as_ptr() as *const c_void,
gl::STATIC_DRAW,
);
// Vertext pointer
gl::VertexAttribPointer(
0,
3,
gl::FLOAT,
gl::FALSE,
5 * size_of::<f32>() as i32,
0 as *const c_void,
);
gl::EnableVertexAttribArray(0);
// Texture pointer
gl::VertexAttribPointer(
1,
2,
gl::FLOAT,
gl::FALSE,
5 * size_of::<f32>() as i32,
(3 * size_of::<f32>()) as *const c_void,
);
gl::EnableVertexAttribArray(1);
// Bind textures
gl::GenTextures(1, &mut texture1 as *mut u32);
gl::ActiveTexture(gl::TEXTURE0);
gl::BindTexture(gl::TEXTURE_2D, texture1);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_WRAP_S,
gl::MIRRORED_REPEAT as i32,
);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_WRAP_R,
gl::MIRRORED_REPEAT as i32,
);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_MIN_FILTER,
gl::LINEAR_MIPMAP_LINEAR as i32,
);
let tex1 = image::open("E:\\Repos\\Rust\\RSOpenGL\\src\\textures\\wall.jpg")
.expect("Failed to load image.")
.into_rgb();
gl::TexImage2D(
gl::TEXTURE_2D,
0,
gl::RGB as i32,
tex1.width() as i32,
tex1.height() as i32,
0,
gl::RGB,
gl::UNSIGNED_BYTE,
tex1.as_ptr() as *const c_void,
);
gl::GenerateMipmap(gl::TEXTURE_2D);
// Texture 2
gl::GenTextures(1, &mut texture2 as *mut u32);
gl::ActiveTexture(gl::TEXTURE1);
gl::BindTexture(gl::TEXTURE_2D, texture2);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_WRAP_S,
gl::MIRRORED_REPEAT as i32,
);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_WRAP_R,
gl::MIRRORED_REPEAT as i32,
);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_MIN_FILTER,
gl::LINEAR_MIPMAP_LINEAR as i32,
);
let tex2 = image::open("E:\\Repos\\Rust\\RSOpenGL\\src\\textures\\awesomeface.png")
.expect("Failed to load image.")
.into_rgb();
gl::TexImage2D(
gl::TEXTURE_2D,
0,
gl::RGB as i32,
tex2.width() as i32,
tex2.height() as i32,
0,
gl::RGB,
gl::UNSIGNED_BYTE,
tex2.as_ptr() as *const c_void,
);
gl::GenerateMipmap(gl::TEXTURE_2D);
gl::ClearColor(0.2, 0.3, 0.3, 1.0);
shader.use_shader();
shader.set_int32("texture1", 0);
shader.set_int32("texture2", 1);
}
let mut last_frame = glfw.get_time();
while window.should_close() == false {
let curr_frame: f64 = glfw.get_time();
let delta_time: f64 = curr_frame - last_frame;
println!("{}", delta_time);
last_frame = curr_frame;
// process input
unsafe {
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
gl::ActiveTexture(gl::TEXTURE0);
gl::BindTexture(gl::TEXTURE_2D, texture1);
gl::ActiveTexture(gl::TEXTURE1);
gl::BindTexture(gl::TEXTURE_2D, texture2);
let projection: glm::Mat4 = glm::ext::perspective::<f32>(
glm::radians(90.0),
800 as f32 / 600 as f32,
0.1,
100.0,
);
shader.set_mat4("projection", projection);
let view: glm::Mat4 = glm::ext::look_at::<f32>(
glm::vec3(0.0, 0.0, 3.0),
glm::vec3(0.0, 0.0, 3.0) + glm::vec3(0.0, 0.0, -1.0),
glm::vec3(0.0, 1.0, 0.0),
);
shader.set_mat4("view", view);
// println!("{:?}\n{:?}", view, projection);
shader.use_shader();
gl::BindVertexArray(vao);
let mut i: f32 = 0.0;
for cube in cube_positions.iter() {
let mut model: glm::Mat4 = glm::mat4(
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
);
model = glm::ext::translate(&model, *cube);
let angle: f32 = 20.0 + i;
i += 1.0;
model = glm::ext::rotate(
&model,
glm::radians(angle) * glfw.get_time() as f32,
glm::vec3(1.0, 0.3, 0.5),
);
shader.set_mat4("model", model);
// println!("{:?}", model);
gl::DrawArrays(gl::TRIANGLES, 0, 36);
}
}
glfw.poll_events();
for (_, event) in glfw::flush_messages(&events) {
handle_window_event(&mut window, event);
}
window.swap_buffers();
}
unsafe {
gl::DeleteVertexArrays(1, &vao);
gl::DeleteBuffers(1, &vbo);
// glfw::ffi::glfwTerminate(); apparently not necessary
}
}
fn handle_window_event(window: &mut glfw::Window, event: glfw::WindowEvent) {
match event {
glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true),
_ => {}
}
}
fn load_gl_functions(window: &mut glfw::Window) {
gl::ClearColor::load_with(|_s| window.get_proc_address("glClearColor"));
gl::Clear::load_with(|_s| window.get_proc_address("glClear"));
gl::GenBuffers::load_with(|_s| window.get_proc_address("glGenBuffers"));
gl::GenVertexArrays::load_with(|_s| window.get_proc_address("glGenVertexArrays"));
gl::BindBuffer::load_with(|_s| window.get_proc_address("glBindBuffer"));
gl::BufferData::load_with(|_s| window.get_proc_address("glBufferData"));
gl::VertexAttribPointer::load_with(|_s| window.get_proc_address("glVertexAttribPointer"));
gl::EnableVertexAttribArray::load_with(|_s| {
window.get_proc_address("glEnableVertexAttribArray")
});
gl::BindVertexArray::load_with(|_s| window.get_proc_address("glBindVertexArray"));
gl::DeleteVertexArrays::load_with(|_s| window.get_proc_address("glDeleteVertexArrays"));
gl::DeleteBuffers::load_with(|_s| window.get_proc_address("glDeleteBuffers"));
gl::GenTextures::load_with(|_s| window.get_proc_address("glGenTextures"));
gl::TexParameteri::load_with(|_s| window.get_proc_address("glTexParameteri"));
gl::TexImage2D::load_with(|_s| window.get_proc_address("glTexImage2D"));
gl::BindTexture::load_with(|_s| window.get_proc_address("glBindTexture"));
gl::ActiveTexture::load_with(|_s| window.get_proc_address("glActiveTexture"));
gl::GenerateMipmap::load_with(|_s| window.get_proc_address("glGenerateMipmap"));
gl::Enable::load_with(|_s| window.get_proc_address("glEnable"));
gl::DrawArrays::load_with(|_s| window.get_proc_address("glDrawArrays"));
}
shader.rs
extern crate gl;
extern crate glfw;
extern crate glm;
pub mod shader {
pub struct Shader {
pub id: u32,
}
impl Shader {
pub fn create_shader(vert_file_path: &str, frag_file_path: &str, window: &mut glfw::Window) -> std::result::Result<Shader, std::io::Error> {
if gl::CreateProgram::is_loaded() == false {
let result = Shader::load_gl_procs(window);
if result == false {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"ERROR::SHADER::CANNOT_LOAD_PROGRAMS",
));
}
}
let vert_text = std::fs::read_to_string(vert_file_path).expect("Unable to read vert file");
let vert_text_ptr = vert_text.as_ptr() as *const *const gl::types::GLchar;
let frag_text = std::fs::read_to_string(frag_file_path).expect("Unable to read frag file");
let frag_text_ptr = frag_text.as_ptr() as *const *const gl::types::GLchar;
//println!("{:?} \n{:?}", vert_text_ptr, frag_text_ptr);
let id: gl::types::GLuint;
unsafe {
let vert_shader = gl::CreateShader(gl::VERTEX_SHADER);
gl::ShaderSource(vert_shader, 1, vert_text_ptr, &0);
gl::CompileShader(vert_shader);
/* STATUS_ACCESS_VIOLATION error
let mut success: i32;
let mut info_log: [gl::types::GLchar; 512] = [0; 512];
gl::GetShaderiv(vert_shader, gl::COMPILE_STATUS, success as *mut i32);
println!("{:?}", success);
if success == 0 {
gl::GetShaderInfoLog(vert_shader, 512, 0 as *mut gl::types::GLsizei, &mut info_log[0]);
for i in info_log.iter() {
print!("{}", i);
}
} */
let frag_shader = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(frag_shader, 1, frag_text_ptr, &0);
gl::CompileShader(frag_shader);
id = gl::CreateProgram();
gl::AttachShader(id, vert_shader);
gl::AttachShader(id, frag_shader);
gl::LinkProgram(id);
gl::DeleteShader(vert_shader);
gl::DeleteShader(frag_shader);
}
let created_shader: Shader = Shader { id: id };
return Ok(created_shader);
}
pub fn load_gl_procs(window: &mut glfw::Window) -> bool {
gl::CreateShader::load_with(|_s| window.get_proc_address("glCreateShader"));
gl::ShaderSource::load_with(|_s| window.get_proc_address("glShaderSource"));
gl::CompileShader::load_with(|_s| window.get_proc_address("glCompileShader"));
gl::GetShaderiv::load_with(|_s| window.get_proc_address("glGetShaderiv"));
gl::CreateProgram::load_with(|_s| window.get_proc_address("glCreateProgram"));
gl::AttachShader::load_with(|_s| window.get_proc_address("glAttachShader"));
gl::LinkProgram::load_with(|_s| window.get_proc_address("glLinkProgram"));
gl::GetProgramiv::load_with(|_s| window.get_proc_address("glGetProgramiv"));
gl::GetShaderInfoLog::load_with(|_s| window.get_proc_address("glGetShaderInfoLog"));
gl::GetProgramInfoLog::load_with(|_s| window.get_proc_address("glGetProgramInfoLog"));
gl::DeleteShader::load_with(|_s| window.get_proc_address("glDeleteShader"));
gl::UseProgram::load_with(|_s| window.get_proc_address("glUseProgram"));
gl::Uniform1i::load_with(|_s| window.get_proc_address("glUniform1i"));
gl::Uniform1f::load_with(|_s| window.get_proc_address("glUniform1f"));
gl::UniformMatrix4fv::load_with(|_s| window.get_proc_address("glUniformMatrix4fv"));
gl::GetUniformLocation::load_with(|_s| window.get_proc_address("glGetUniformLocation"));
// TODO Check to see if all of these are loaded
return true;
}
pub unsafe fn use_shader(&self) {
gl::UseProgram(self.id as gl::types::GLuint);
}
pub unsafe fn set_bool(&self, name: &str, value: bool) {
gl::Uniform1i(gl::GetUniformLocation(self.id, name.as_ptr() as *const gl::types::GLchar), value as gl::types::GLint);
}
pub unsafe fn set_int32(&self, name: &str, value: i32) {
gl::Uniform1i(gl::GetUniformLocation(self.id, name.as_ptr() as *const gl::types::GLchar), value as gl::types::GLint);
}
pub unsafe fn set_float32(&self, name: &str, value: f32) {
gl::Uniform1f(gl::GetUniformLocation(self.id, name.as_ptr() as *const gl::types::GLchar), value as gl::types::GLfloat);
}
pub unsafe fn set_mat4(&self, name: &str, value: glm::Mat4) {
gl::UniformMatrix4fv(gl::GetUniformLocation(self.id, name.as_ptr() as *const gl::types::GLchar), 1, gl::FALSE, &value[0][0]);
}
}
}
vertShader.vert
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
out vec2 TexCoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPos, 1.0);
TexCoord = aTexCoord;
}
fragShader.frag
#version 330 core
out vec4 FragColor;
in vec2 TexCoord;
uniform sampler2D texture1;
uniform sampler2D texture2;
void main()
{
// FragColor = vec4(ourColor, 1.0f);
FragColor = mix(texture(texture1, TexCoord), texture(texture2, TexCoord), 0.5);
}
There were actually two main problems with my program, both regarding CStrings.
Problem 1: OpenGL couldn't create the program because the text I sent it did not have a null termination character, so it had to be recasted as a CString with one.
let v_shader_code = CString::new(vert_text.as_bytes()).unwrap();
let f_shader_code = CString::new(frag_text.as_bytes()).unwrap();
Problem 2: The "set_*()" functions wouldn't work because the name was being passed as an &str without a null termination character. This also has to be cast into a c string.
pub unsafe fn set_bool(&self, name: &str, value: bool) {
gl::Uniform1i(gl::GetUniformLocation(self.id, CString::new(name).expect("Error converting &str to CString").as_c_str().as_ptr()), value as i32);
}

Error LSTM sentiment analysis using Tensorflow - ValueError: Cannot feed value of shape

I am learning LSTM model for sentiment analysis.
Below is the code that generates the feature sets from 5000 positive and negative sentences:
import nltk
from nltk.tokenize import word_tokenize
import numpy as np
import random
from collections import Counter
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
hm_lines = 100000
def create_lexicon(pos, neg):
lexicon = []
with open(pos, 'r') as f:
contents = f.readlines()
for l in contents[:len(contents)]:
l= l.decode('utf-8')
all_words = word_tokenize(l)
lexicon += list(all_words)
f.close()
with open(neg, 'r') as f:
contents = f.readlines()
for l in contents[:len(contents)]:
l= l.decode('utf-8')
all_words = word_tokenize(l)
lexicon += list(all_words)
f.close()
lexicon = [lemmatizer.lemmatize(i) for i in lexicon]
w_counts = Counter(lexicon)
l2 = []
for w in w_counts:
if 1000 > w_counts[w] > 50:
l2.append(w)
print("Lexicon length create_lexicon: ",len(lexicon))
return l2
def sample_handling(sample, lexicon, classification):
featureset = []
print("Lexicon length Sample handling: ",len(lexicon))
with open(sample, 'r') as f:
contents = f.readlines()
for l in contents[:len(contents)]:
l= l.decode('utf-8')
current_words = word_tokenize(l.lower())
current_words= [lemmatizer.lemmatize(i) for i in current_words]
features = np.zeros(len(lexicon))
for word in current_words:
if word.lower() in lexicon:
index_value = lexicon.index(word.lower())
features[index_value] +=1
features = list(features)
featureset.append([features, classification])
f.close()
print("Feature SET------")
print(len(featureset))
return featureset
def create_feature_sets_and_labels(pos, neg, test_size = 0.1):
global m_lexicon
m_lexicon = create_lexicon(pos, neg)
features = []
features += sample_handling(pos, m_lexicon, [1,0])
features += sample_handling(neg, m_lexicon, [0,1])
random.shuffle(features)
features = np.array(features)
testing_size = int(test_size * len(features))
train_x = list(features[:,0][:-testing_size])
train_y = list(features[:,1][:-testing_size])
test_x = list(features[:,0][-testing_size:])
test_y = list(features[:,1][-testing_size:])
return train_x, train_y, test_x, test_y
def get_lexicon():
global m_lexicon
return m_lexicon
Below is the code for LSTM:
import tensorflow as tf
from tensorflow.contrib import rnn
from create_sentiment_featuresets import create_feature_sets_and_labels
from create_sentiment_featuresets import get_lexicon
import numpy as np
# extras for testing
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
#- end extras
train_x, train_y, test_x, test_y = create_feature_sets_and_labels('pos.txt', 'neg.txt')
print(len(train_x))
print(len(train_x[0]))
input_vec_size= len(train_x[0]) # = lstm size
hm_epochs = 3
n_classes = 2
batch_size = 100
rnn_size = 128 # hidden layers
x = tf.placeholder('float', [None, input_vec_size, n_classes])
y = tf.placeholder('float')
def recurrent_neural_network(x):
layer = {'weights': tf.Variable(tf.random_normal([rnn_size, n_classes])), 'biases': tf.Variable(tf.random_normal([n_classes]))}
x = tf.transpose(x, [1,0,2])
x = tf.reshape(x, [-1, input_vec_size])
x = tf.split(x, 2, 0)
lstm_cell = rnn.BasicLSTMCell(rnn_size, state_is_tuple=True)
outputs, states = rnn.static_rnn(lstm_cell, x, dtype= tf.float32)
output = tf.matmul(outputs[-1], layer['weights']) + layer['biases']
return output
def train_neural_network(x):
prediction = recurrent_neural_network(x)
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits= prediction, labels= y))
optimizer = tf.train.AdamOptimizer(learning_rate= 0.001).minimize(cost)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(hm_epochs):
epoch_loss = 0
i = 0
while i < len(train_x):
start = i
end = i+ batch_size
batch_x = train_x[start: end]
batch_y = train_y[start: end]
_, c = sess.run([optimizer, cost], feed_dict= {x: batch_x, y: batch_y})
epoch_loss += c
i+= batch_size
print('Epoch', epoch+ 1, 'completed out of ', hm_epochs, 'loss:', epoch_loss)
correct= tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:', accuracy.eval({x:test_x, y:test_y}))
# prediction for single --------------
m_lexicon= get_lexicon()
print('Lexicon length: ',len(m_lexicon))
input_data= "David likes to go out with Kary"
current_words= word_tokenize(input_data.lower())
current_words = [lemmatizer.lemmatize(i) for i in current_words]
features = np.zeros(len(m_lexicon))
for word in current_words:
if word.lower() in m_lexicon:
index_value = m_lexicon.index(word.lower())
features[index_value] +=1
features = np.array(list(features)).reshape(1,-1) # if reshape is remove, add x:[features]
print('features length: ',len(features))
result = sess.run(tf.argmax(prediction.eval(feed_dict={x:features}), 1))
print('RESULT: ', result)
print(prediction.eval(feed_dict={x:features}))
if result[0] == 0:
print('Positive: ', input_data)
elif result[0] == 1:
print('Negative: ', input_data)
train_neural_network(x)
The above code is giving the following error:
2017-06-07 16:36:52.775649: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-07 16:36:52.775682: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-07 16:36:52.775702: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-06-07 16:36:52.775714: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-07 16:36:52.775724: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-06-07 16:36:53.094522: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-06-07 16:36:53.094925: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with properties:
name: GeForce 930MX
major: 5 minor: 0 memoryClockRate (GHz) 1.0195
pciBusID 0000:01:00.0
Total memory: 1.96GiB
Free memory: 1.76GiB
2017-06-07 16:36:53.094958: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0
2017-06-07 16:36:53.094966: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0: Y
2017-06-07 16:36:53.094975: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce 930MX, pci bus id: 0000:01:00.0)
Traceback (most recent call last):
File "sentiment_demo_lstm2.py", line 119, in <module>
train_neural_network(x)
File "sentiment_demo_lstm2.py", line 79, in train_neural_network
_, c = sess.run([optimizer, cost], feed_dict= {x: batch_x, y: batch_y})
File "/home/lsmpc/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 778, in run
run_metadata_ptr)
File "/home/lsmpc/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 961, in _run
% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (100, 423) for Tensor u'Placeholder:0', which has shape '(?, 423, 2)'
Please help.
Also I am having difficulty understanding this part:
x = tf.transpose(x, [1,0,2])
x = tf.reshape(x, [-1, input_vec_size])
x = tf.split(x, 2, 0)
Output of
print(train_x[0])
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
print(train_y[0])
[0, 1]
len(train_x)= 9596, len(train_x[0]) = 423
Thanks.

No matching function to call to std::vector<float>

I am writing a code for 3D world to 2D projection and as i try to push back coordinates in my vectors it gives me this error that there is no matching function to call to std::vector.
#include <X11/Xlib.h>
#include "draw.h"
#include "points.h"
#include "unistd.h"
#include <math.h>
#include <vector>
void draw(Display* d, Window w, GC gc)
{
std::vector<float> xpoints;
xpoints.push_back (-1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0);
std::vector<float> ypoints;
ypoints.push_back (1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0);
std::vector<float> zpoints;
zpoints.push_back (-1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0);
for (;;)
{
XClearWindow(d, w);
for (unsigned int c = 0; c < xpoints.size(); c++)
{
XDrawLine(d, w, gc, xpoints.at(c), ypoints.at(c), xpoints.at(c+1), ypoints.at(c+1));
}
XFlush(d);
usleep(16666);
}
}
You cannot push multiple values at once using push_back:
xpoints.push_back (-1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0);
If you are using c++11 you should directly initialize your vector:
std::vector<float> xpoints{-1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0};
Just include the vector header:
#include <vector>

Unexpected behaviour with GLSL Matrix

The following simple fragment shader exhibits very odd behaviour. Without the loop the output is all red, as expected. But with the loop it turns yellow, i. e. rgb(1,1,0). Might someone enlighten me as to what is happening here?
void main(void)
{
mat4 redUnit = mat4(
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0
);
mat4 greenUnit = mat4(
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0
);
mat4 blueUnit = mat4(
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0
);
for (int x = -1; x < 3; x++) {
for (int y = -1; y < 3; y++) {
redUnit[x+1][y+1] = 1.0;
greenUnit[x+1][y+1] = 0.0;
blueUnit[x+1][y+1] = 0.0;
}
}
gl_FragColor = vec4(redUnit[0][0], greenUnit[0][0], blueUnit[0][0], 1.0);
}
EDIT: The output color depends on the order in which the variables are declared. So somehow memory boundaries are being violated. Still doesn't explain the behaviour though.
In case anyone else encounters this: It is a bug in the Intel GMA graphics driver. On another machine with a different graphics card everything works just fine.