Пример #1
0
void OpenglBufferData::loadBufferData() {
	if (!theModelView)
		return;
	SimMesh *theMesh = theModelView->theMesh;
	MeshColor *theColor = theModelView->theColor;
	MeshTexture *theTexture = theModelView->theTexture;
	MeshNormal *theNormals = theModelView->theNormals;
	vertex *data = NULL;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	if (!theTexture) {
		data = new vertex[theMesh->numVertices()];
		for (size_t i = 0; i < theMesh->numVertices(); i++) {
			data[i].position = vec4(theMesh->indVertex(i)->p[0], theMesh->indVertex(i)->p[1], theMesh->indVertex(i)->p[2], 1.0f);
			if (theModelView->theColor) {
				GLfloat a = 1.0f;
				if (i < theColor->a.size()) a = theColor->a[i] / 255.0f;
				data[i].color = vec4(theColor->r[i] / 255.0f, theColor->g[i] / 255.0f, theColor->b[i] / 255.0f, a);
			}
			else
				data[i].color = vec4(theModelView->color[0], theModelView->color[1], theModelView->color[2], 1.0f);
		}
		if (theNormals) {
			for (size_t i = 0; i < theNormals->vNormals.size(); i++) {
				data[i].normal = vec3(theNormals->vNormals[i][0], theNormals->vNormals[i][1], theNormals->vNormals[i][2]);
			}
		}
		glBufferData(GL_ARRAY_BUFFER, theMesh->numVertices() * sizeof(vertex), data, GL_STATIC_DRAW);
	}
	else {
		// if texture exists, we need to duplicate the vertex on each triangle
		data = new vertex[theMesh->numFaces() * 3];
		for (size_t i = 0; i < theMesh->numFaces(); i++) {
			SimFace *f = theMesh->indFace(i);
			for (int j = 0; j < 3; j++) {
				SimVertex *v = f->ver[j];
				data[i * 3 + j].position = vec4(theMesh->indVertex(v->idx)->p[0], theMesh->indVertex(v->idx)->p[1], theMesh->indVertex(v->idx)->p[2], 1.0);
				if (theNormals) {
					data[i * 3 + j].normal = vec3(theNormals->vNormals[v->idx][0], theNormals->vNormals[v->idx][1], theNormals->vNormals[v->idx][2]);
					data[i * 3 + j].tangent = vec3(theModelView->tangents[i * 3 + j][0], theModelView->tangents[i * 3 + j][1], theModelView->tangents[i * 3 + j][2]);
				}
				data[i * 3 + j].texCoord = vec2(theTexture->getU(v, f), theTexture->getV(v, f));
			}
		}
		glBufferData(GL_ARRAY_BUFFER, 3 * theMesh->numFaces() * sizeof(vertex), data, GL_STATIC_DRAW);
	}

	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0));
	if (theTexture) {
		glEnableVertexAttribArray(3);
		glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(2 * sizeof(vec4) + sizeof(vec3)));
		if (theNormals) {
			glEnableVertexAttribArray(4);
			glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(2 * sizeof(vec4) + sizeof(vec3) + sizeof(vec2)));
		}
	}
	else {
		glEnableVertexAttribArray(1);
		glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(sizeof(vec4)));
	}
	if (theNormals) {
		glEnableVertexAttribArray(2);
		glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(2 * sizeof(vec4)));
	}
	unsigned int *face_indices = new unsigned int[3 * theMesh->numFaces()];
	for (size_t i = 0; i < theMesh->numFaces(); i++) {
		SimFace *f = theMesh->indFace(i);
		for (int j = 0; j < 3; j++) {
			if (!theTexture) 
				face_indices[3 * i + j] = f->ver[j]->idx;
			else 
				face_indices[3 * i + j] = 3 * i + j;
		}
	}
	glGenBuffers(1, &vbo_face_indices);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_face_indices);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * theMesh->numFaces() * sizeof(unsigned int), face_indices, GL_STATIC_DRAW);
	glGenVertexArrays(1, &vao_wireFrame);
	glBindVertexArray(vao_wireFrame);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0));
	unsigned int *edge_indices = new unsigned int[2 * theMesh->numEdges()];
	if (theTexture) {
		for (size_t i = 0; i < theMesh->numFaces(); i++) {
			SimFace *f = theMesh->indFace(i);
			for (int j = 0; j < 3; j++) {
				SimEdge * e = theMesh->idEdge(f->ver[j]->idx, f->ver[(j + 1) % 3]->idx);
				edge_indices[2 * e->idx + 0] = i * 3 + j;
				edge_indices[2 * e->idx + 1] = i * 3 + (j + 1) % 3;
			}
		}
	}
	else {
		for (size_t i = 0; i < theMesh->numEdges(); i++) {
			SimEdge * e = theMesh->indEdge(i);
			edge_indices[2 * i + 0] = e->v0->idx;
			edge_indices[2 * i + 1] = e->v1->idx;
		}
	}
	
	glGenBuffers(1, &vbo_edge_indices);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_edge_indices);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 2 * theMesh->numEdges() * sizeof(unsigned int), edge_indices, GL_STATIC_DRAW);
	if (theTexture) {
		glGenTextures(1, &texture);
		glBindTexture(GL_TEXTURE_2D, texture);
			//get the OpenGL-friendly image
		QImage GL_formatted_image = QGLWidget::convertToGLFormat(QImage(theModelView->theTexture->texture_filename.c_str()));
		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);
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
					//generate the texture
		glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, GL_formatted_image.width(),
		GL_formatted_image.height(),
		0, GL_RGBA, GL_UNSIGNED_BYTE, GL_formatted_image.bits() );
		glBindTexture(GL_TEXTURE_2D, 0);
		//QImage GL_formatted_image2 = QGLWidget::convertToGLFormat(QImage("normal.bmp"));
		//glGenTextures(1, &normalTexture);
		//glBindTexture(GL_TEXTURE_2D, normalTexture);
		////get the OpenGL-friendly image
		//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);
		//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		////generate the texture
		//glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, GL_formatted_image2.width(),
		//	GL_formatted_image2.height(),
		//	0, GL_RGBA, GL_UNSIGNED_BYTE, GL_formatted_image2.bits() );
		//glBindTexture(GL_TEXTURE_2D, 0);
		
	}

	delete []data;
	delete []edge_indices;
	delete []face_indices;
}
Пример #2
0
vec3 VoxelFile::get_min()
{
    return vec3(x_offset, y_offset, z_offset);
}
Пример #3
0
void VoxelModel::draw_immediate(float alpha, bool offset)
{
    int x_offset, y_offset, z_offset;
    if (offset) {
        x_offset = file->x_offset;
        y_offset = file->y_offset;
        z_offset = file->z_offset;
    } else
        x_offset = y_offset = z_offset = 0;

    glBegin(GL_QUADS);
    unsigned char alpha_c = (unsigned char)(alpha * 255.0f);
    int x, y, z;
    for (x = 0; x < file->x_size; x++)
    for (y = 0; y < file->y_size; y++)
    for (z = 0; z < file->z_size; z++) {
        unsigned char color = file->get(x, y, z);
        if (color == VOXEL_AIR)
            continue;
        RGBColor & color2 = global_palette[color];

        float noise = glm::simplex(vec3(x, y, z));
        vec3 color3 = vec3(color2.r, color2.g, color2.b);
        color3 *= (1.0f + noise * 0.01f);
        color3 = glm::clamp(color3, 0, 255);

        glColor4ub(int(color3.x), int(color3.y), int(color3.z), alpha_c);

        float gl_x1 = float(x + x_offset);
        float gl_x2 = gl_x1 + 1.0f;
        float gl_y1 = float(y + y_offset);
        float gl_y2 = gl_y1 + 1.0f;
        float gl_z1 = float(z + z_offset);
        float gl_z2 = gl_z1 + 1.0f;

        // Left Face
        if (!file->is_solid(x, y + 1, z)) {
            glNormal3f(0.0f, 1.0f, 0.0f);
            glVertex3f(gl_x1, gl_y2, gl_z1);
            glVertex3f(gl_x1, gl_y2, gl_z2);
            glVertex3f(gl_x2, gl_y2, gl_z2);
            glVertex3f(gl_x2, gl_y2, gl_z1);
        }

        // Right face
        if (!file->is_solid(x, y - 1, z)) {
            glNormal3f(0.0f, -1.0f, 0.0f);
            glVertex3f(gl_x1, gl_y1, gl_z1); // Top right
            glVertex3f(gl_x2, gl_y1, gl_z1); // Top left
            glVertex3f(gl_x2, gl_y1, gl_z2); // Bottom left
            glVertex3f(gl_x1, gl_y1, gl_z2); // Bottom right
        }

        // Top face
        if (!file->is_solid(x, y, z + 1)) {
            glNormal3f(0.0f, 0.0f, -1.0f);
            glVertex3f(gl_x1, gl_y1, gl_z2); // Bottom left
            glVertex3f(gl_x2, gl_y1, gl_z2); // Bottom right
            glVertex3f(gl_x2, gl_y2, gl_z2); // Top right
            glVertex3f(gl_x1, gl_y2, gl_z2); // Top left
        }

        // Bottom face
        if (!file->is_solid(x, y, z - 1)) {
            glNormal3f(0.0f, 0.0f, 1.0f);
            glVertex3f(gl_x1, gl_y1, gl_z1); // Bottom right
            glVertex3f(gl_x1, gl_y2, gl_z1); // Top right
            glVertex3f(gl_x2, gl_y2, gl_z1); // Top left
            glVertex3f(gl_x2, gl_y1, gl_z1); // Bottom left
        }

        // Right face
        if (!file->is_solid(x + 1, y, z)) {
            glNormal3f(1.0f, 0.0f, 0.0f);
            glVertex3f(gl_x2, gl_y1, gl_z1); // Bottom right
            glVertex3f(gl_x2, gl_y2, gl_z1); // Top right
            glVertex3f(gl_x2, gl_y2, gl_z2); // Top left
            glVertex3f(gl_x2, gl_y1, gl_z2); // Bottom left
        }

        // Left Face
        if (!file->is_solid(x - 1, y, z)) {
            glNormal3f(-1.0f, 0.0f, 0.0f);
            glVertex3f(gl_x1, gl_y1, gl_z1); // Bottom left
            glVertex3f(gl_x1, gl_y1, gl_z2); // Bottom right
            glVertex3f(gl_x1, gl_y2, gl_z2); // Top right
            glVertex3f(gl_x1, gl_y2, gl_z1); // Top left
        }
    }
    glEnd();
}
Пример #4
0
vec3 Matrix44::forward()
{
    return -vec3(m_data[8], m_data[9], m_data[10]);
}
Пример #5
0
vec3 Matrix44::getTranslation()
{
	return vec3(m_data[12], m_data[13], m_data[14]);
}
Пример #6
0
 layerParam::layerParam() : 
     position(vec2(0.f)), scale(vec2(1.f)), hsb_bias(vec3(0.f)),
     hsb_mod(vec3(1.f)), color_bias(vec4(0.f)), color_mod(vec4(1.f)), 
     blend(BLEND_REPLACE)
 {
 }
Пример #7
0
vec3 Matrix44::transformVec3(vec3 v)
{
    auto result = *this * vec4(v, 1.0f);
    return vec3(result.x, result.y, result.z);
}
Пример #8
0
OrientationOverlay::OrientationOverlay()
    : ImageProcessor("image/orientationoverlay")
    , inport_(Port::INPORT, "image.input", "Image Input")
    , outport_(Port::OUTPORT, "image.output", "Image Output")
    , privatePort_(Port::OUTPORT, "image.tmp", "image.tmp", false)
    , drawCube_("drawCube", "Draw Cube", true)
    , drawAxes_("drawAxes", "Draw Axes", false)
    , drawTextures_("drawTextures", "Draw Cube Textures", true)
    , colorizeTextures_("colorizeTextures", "Colorize Textures", false)
    , filenameFront_("filenameFront", "Front Texture", "Select texture",
                VoreenApplication::app()->getUserDataPath("textures"), "*.jpg;*.png;*.bmp",
                FileDialogProperty::OPEN_FILE)
    , filenameBack_("filenameBack", "Back Texture", "Select texture",
                VoreenApplication::app()->getUserDataPath("textures"), "*.jpg;*.png;*.bmp",
                FileDialogProperty::OPEN_FILE)
    , filenameTop_("filenameTop", "Top Texture", "Select texture",
                VoreenApplication::app()->getUserDataPath("textures"), "*.jpg;*.png;*.bmp",
                FileDialogProperty::OPEN_FILE)
    , filenameBottom_("filenameBottom", "Bottom Texture", "Select texture",
                VoreenApplication::app()->getUserDataPath("textures"), "*.jpg;*.png;*.bmp",
                FileDialogProperty::OPEN_FILE)
    , filenameLeft_("filenameLeft", "Left Texture", "Select texture",
                VoreenApplication::app()->getUserDataPath("textures"), "*.jpg;*.png;*.bmp",
                FileDialogProperty::OPEN_FILE)
    , filenameRight_("filenameRight", "Right Texture", "Select texture",
                VoreenApplication::app()->getUserDataPath("textures"), "*.jpg;*.png;*.bmp",
                FileDialogProperty::OPEN_FILE)
    , shiftX_("shiftX", "Horizontal Position", 0.85f, 0.0f, 1.0f)
    , shiftY_("shiftY", "Vertical Position", 0.15f, 0.0f, 1.0f)
    , cubeSize_("cubeSize", "Cube Size", 0.15f, 0.05, 1)
    , axisLength_("axisLength", "Axes Length", 0.15f, 0.1, 4.f)
    , camera_("camera", "Camera", tgt::Camera(vec3(0.f, 0.f, 3.5f), vec3(0.f, 0.f, 0.f), vec3(0.f, 1.f, 0.f)))
    , frontTex_(0)
    , backTex_(0)
    , topTex_(0)
    , leftTex_(0)
    , bottomTex_(0)
    , rightTex_(0)
    , reloadTextures_(false)
    , loadingTextures_(false)
{
    addPort(inport_);
    addPort(outport_);
    addPrivateRenderPort(&privatePort_);

    addProperty(drawCube_);
    addProperty(drawAxes_);
    addProperty(drawTextures_);
    filenameFront_.onChange(CallMemberAction<OrientationOverlay>(this, &OrientationOverlay::reloadTextures));
    addProperty(colorizeTextures_);
    addProperty(filenameFront_);
    filenameBack_.onChange(CallMemberAction<OrientationOverlay>(this, &OrientationOverlay::reloadTextures));
    addProperty(filenameBack_);
    filenameTop_.onChange(CallMemberAction<OrientationOverlay>(this, &OrientationOverlay::reloadTextures));
    addProperty(filenameTop_);
    filenameBottom_.onChange(CallMemberAction<OrientationOverlay>(this, &OrientationOverlay::reloadTextures));
    addProperty(filenameBottom_);
    filenameLeft_.onChange(CallMemberAction<OrientationOverlay>(this, &OrientationOverlay::reloadTextures));
    addProperty(filenameLeft_);
    filenameRight_.onChange(CallMemberAction<OrientationOverlay>(this, &OrientationOverlay::reloadTextures));
    addProperty(filenameRight_);
    addProperty(shiftX_);
    addProperty(shiftY_);
    addProperty(cubeSize_);
    addProperty(axisLength_);
    addProperty(camera_);

    // set initial texture names
    std::string texturePath = VoreenApplication::app()->getResourcePath("textures");
    textureNames_[0] = texturePath + "/axial_t.png";
    textureNames_[1] = texturePath + "/axial_b.png";
    textureNames_[2] = texturePath + "/coronal_f.png";
    textureNames_[3] = texturePath + "/coronal_b.png";
    textureNames_[4] = texturePath + "/sagittal_l.png";
    textureNames_[5] = texturePath + "/sagittal_r.png";
}
Пример #9
0
int main () {
	assert (restart_gl_log ());
	assert (start_gl ());
	
	reserve_video_memory ();

	// tell GL to only draw onto a pixel if the shape is closer to the viewer
	glEnable (GL_DEPTH_TEST); // enable depth-testing
	glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer"

	GLfloat points[] = {
		-0.5f, -0.5f,  0.0f,
		 0.5f, -0.5f,  0.0f,
		 0.5f,  0.5f,  0.0f,
		 0.5f,  0.5f,  0.0f,
		-0.5f,  0.5f,  0.0f,
		-0.5f, -0.5f,  0.0f
	};
	
	GLfloat texcoords[] = {
		0.0f, 0.0f,
		1.0f, 0.0f,
		1.0f, 1.0f,
		1.0f, 1.0f,
		0.0f, 1.0f,
		0.0f, 0.0f
	};
	
	GLuint points_vbo;
	glGenBuffers (1, &points_vbo);
	glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
	glBufferData (GL_ARRAY_BUFFER, 18 * sizeof (GLfloat), points, GL_STATIC_DRAW);
	
	GLuint texcoords_vbo;
	glGenBuffers (1, &texcoords_vbo);
	glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
	glBufferData (GL_ARRAY_BUFFER, 12 * sizeof (GLfloat), texcoords, GL_STATIC_DRAW);
	
	GLuint vao;
	glGenVertexArrays (1, &vao);
	glBindVertexArray (vao);
	glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
	glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
	glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
	glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
	glEnableVertexAttribArray (0);
	glEnableVertexAttribArray (1);
	
	GLuint shader_programme = create_programme_from_files (
		"test_vs.glsl", "test_fs.glsl");
	
	#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
	// input variables
	float near = 0.1f; // clipping plane
	float far = 100.0f; // clipping plane
	float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians
	float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
	// matrix components
	float range = tan (fov * 0.5f) * near;
	float Sx = (2.0f * near) / (range * aspect + range * aspect);
	float Sy = near / range;
	float Sz = -(far + near) / (far - near);
	float Pz = -(2.0f * far * near) / (far - near);
	GLfloat proj_mat[] = {
		Sx, 0.0f, 0.0f, 0.0f,
		0.0f, Sy, 0.0f, 0.0f,
		0.0f, 0.0f, Sz, -1.0f,
		0.0f, 0.0f, Pz, 0.0f
	};
	
		
	float cam_speed = 1.0f; // 1 unit per second
	float cam_yaw_speed = 10.0f; // 10 degrees per second
	float cam_pos[] = {0.0f, 0.0f, 2.0f}; // don't start at zero, or we will be too close
	float cam_yaw = 0.0f; // y-rotation in degrees
	mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2]));
	mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw);
	mat4 view_mat = R * T;
	
	int view_mat_location = glGetUniformLocation (shader_programme, "view");
	glUseProgram (shader_programme);
	glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
	int proj_mat_location = glGetUniformLocation (shader_programme, "proj");
	glUseProgram (shader_programme);
	glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat);
	
	// load texture
	GLuint tex;
	assert (load_texture ("skulluvmap.png", &tex));
	
	
	glEnable (GL_CULL_FACE); // cull face
	glCullFace (GL_BACK); // cull back face
	glFrontFace (GL_CCW); // GL_CCW for counter clock-wise
	
	// initialise timers
	bool dump_video = false;
	double video_timer = 0.0; // time video has been recording
	double video_dump_timer = 0.0; // timer for next frame grab
	double frame_time = 0.04; // 1/25 seconds of time
	
	while (!glfwWindowShouldClose (g_window)) {
		static double previous_seconds = glfwGetTime ();
		double current_seconds = glfwGetTime ();
		double elapsed_seconds = current_seconds - previous_seconds;
		previous_seconds = current_seconds;
		
		if (dump_video) {
			// elapsed_seconds is seconds since last loop iteration
			video_timer += elapsed_seconds;
			video_dump_timer += elapsed_seconds;
			// only record 10s of video, then quit
			if (video_timer > 10.0) {
				break;
			}
		}
	
		_update_fps_counter (g_window);
		// wipe the drawing surface clear
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport (0, 0, g_gl_width, g_gl_height);
		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);
		// draw points 0-3 from the currently bound VAO with current in-use shader
		glDrawArrays (GL_TRIANGLES, 0, 6);
		// update other events like input handling 
		glfwPollEvents ();
		
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_F11)) {
			dump_video = true;
		}
		
		// control keys
		bool cam_moved = false;
		if (glfwGetKey (g_window, GLFW_KEY_A)) {
			cam_pos[0] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_D)) {
			cam_pos[0] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) {
			cam_pos[1] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) {
			cam_pos[1] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_W)) {
			cam_pos[2] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_S)) {
			cam_pos[2] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_LEFT)) {
			cam_yaw += cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) {
			cam_yaw -= cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		// update view matrix
		if (cam_moved) {
			mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2])); // cam translation
			mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // 
			mat4 view_mat = R * T;
			glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
		}
		
		
		if (dump_video) { // check if recording mode is enabled
			while (video_dump_timer > frame_time) {
				grab_video_frame (); // 25 Hz so grab a frame
				video_dump_timer -= frame_time;
			}
		}
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (g_window, 1);
		}
		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (g_window);
	}
	
	if (dump_video) {
		dump_video_frames ();
	}
	
	// close GL context and any other GLFW resources
	glfwTerminate();
	return 0;
}
Пример #10
0
int main () {
	assert (restart_gl_log ());
/*------------------------------start GL context------------------------------*/
	assert (start_gl ());

/*------------------------------create geometry-------------------------------*/
	GLfloat points[] = {
		 0.0f,	0.5f,	0.0f,
		 0.5f, -0.5f,	0.0f,
		-0.5f, -0.5f,	0.0f
	};
	
	GLfloat colours[] = {
		1.0f, 0.0f,  0.0f,
		0.0f, 1.0f,  0.0f,
		0.0f, 0.0f,  1.0f
	};
	
	GLuint points_vbo;
	glGenBuffers (1, &points_vbo);
	glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
	glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (GLfloat), points, GL_STATIC_DRAW);
	
	GLuint colours_vbo;
	glGenBuffers (1, &colours_vbo);
	glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
	glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (GLfloat), colours, GL_STATIC_DRAW);
	
	GLuint vao;
	glGenVertexArrays (1, &vao);
	glBindVertexArray (vao);
	glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
	glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
	glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
	glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
	glEnableVertexAttribArray (0);
	glEnableVertexAttribArray (1);

/*------------------------------create shaders--------------------------------*/
	char vertex_shader[1024 * 256];
	char fragment_shader[1024 * 256];
	assert (parse_file_into_str ("Shaders/test_vs.glsl", vertex_shader, 1024 * 256));
	assert (parse_file_into_str ("Shaders/test_fs.glsl", fragment_shader, 1024 * 256));
	
	GLuint vs = glCreateShader (GL_VERTEX_SHADER);
	const GLchar* p = (const GLchar*)vertex_shader;
	glShaderSource (vs, 1, &p, NULL);
	glCompileShader (vs);
	
	// check for compile errors
	int params = -1;
	glGetShaderiv (vs, GL_COMPILE_STATUS, &params);
	if (GL_TRUE != params) {
		fprintf (stderr, "ERROR: GL shader index %i did not compile\n", vs);
		print_shader_info_log (vs);
		return 1; // or exit or something
	}
	
	GLuint fs = glCreateShader (GL_FRAGMENT_SHADER);
	p = (const GLchar*)fragment_shader;
	glShaderSource (fs, 1, &p, NULL);
	glCompileShader (fs);
	
	// check for compile errors
	glGetShaderiv (fs, GL_COMPILE_STATUS, &params);
	if (GL_TRUE != params) {
		fprintf (stderr, "ERROR: GL shader index %i did not compile\n", fs);
		print_shader_info_log (fs);
		return 1; // or exit or something
	}
	
	GLuint shader_programme = glCreateProgram ();
	glAttachShader (shader_programme, fs);
	glAttachShader (shader_programme, vs);
	glLinkProgram (shader_programme);
	
	glGetProgramiv (shader_programme, GL_LINK_STATUS, &params);
	if (GL_TRUE != params) {
		fprintf (
			stderr,
			"ERROR: could not link shader programme GL index %i\n",
			shader_programme
		);
		print_programme_info_log (shader_programme);
		return false;
	}
	
/*--------------------------create camera matrices----------------------------*/
	/* create PROJECTION MATRIX */
	#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
	// input variables
	float near = 0.1f; // clipping plane
	float far = 100.0f; // clipping plane
	float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians
	float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
	// matrix components
	float range = tan (fov * 0.5f) * near;
	float Sx = (2.0f * near) / (range * aspect + range * aspect);
	float Sy = near / range;
	float Sz = -(far + near) / (far - near);
	float Pz = -(2.0f * far * near) / (far - near);
	GLfloat proj_mat[] = {
		Sx, 0.0f, 0.0f, 0.0f,
		0.0f, Sy, 0.0f, 0.0f,
		0.0f, 0.0f, Sz, -1.0f,
		0.0f, 0.0f, Pz, 0.0f
	};
	
	/* create VIEW MATRIX */
	float cam_speed = 1.0f; // 1 unit per second
	float cam_yaw_speed = 10.0f; // 10 degrees per second
	float cam_pos[] = {0.0f, 0.0f, 2.0f}; // don't start at zero, or we will be too close
	float cam_yaw = 0.0f; // y-rotation in degrees
	mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2]));
	mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw);
	mat4 view_mat = R * T;
	
	/* get location numbers of matrices in shader programme */
	GLint view_mat_location = glGetUniformLocation (shader_programme, "view");
	GLint proj_mat_location = glGetUniformLocation (shader_programme, "proj");
	/* use program (make current in state machine) and set default matrix values*/
	glUseProgram (shader_programme);
	glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
	glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat);
	
/*------------------------------rendering loop--------------------------------*/
	/* some rendering defaults */
	glEnable (GL_CULL_FACE); // cull face
	glCullFace (GL_BACK); // cull back face
	glFrontFace (GL_CW); // GL_CCW for counter clock-wise
	
	while (!glfwWindowShouldClose (g_window)) {
		static double previous_seconds = glfwGetTime ();
		double current_seconds = glfwGetTime ();
		double elapsed_seconds = current_seconds - previous_seconds;
		previous_seconds = current_seconds;
	
		_update_fps_counter (g_window);
		// wipe the drawing surface clear
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport (0, 0, g_gl_width, g_gl_height);
		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);
		// draw points 0-3 from the currently bound VAO with current in-use shader
		glDrawArrays (GL_TRIANGLES, 0, 3);
		// update other events like input handling 
		glfwPollEvents ();
		
/*-----------------------------move camera here-------------------------------*/
		// control keys
		bool cam_moved = false;
		if (glfwGetKey (g_window, GLFW_KEY_A)) {
			cam_pos[0] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_D)) {
			cam_pos[0] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) {
			cam_pos[1] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) {
			cam_pos[1] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_W)) {
			cam_pos[2] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_S)) {
			cam_pos[2] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_LEFT)) {
			cam_yaw += cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) {
			cam_yaw -= cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		/* update view matrix */
		if (cam_moved) {
			mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2])); // cam translation
			mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // 
			mat4 view_mat = R * T;
			glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
		}
		
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (g_window, 1);
		}
		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (g_window);
	}
	
	// close GL context and any other GLFW resources
	glfwTerminate();
	return 0;
}
Пример #11
0
void World::handle_event() {

	auto &what = *this->context().event;
  auto& window = *this->context().window;
  auto& camera = *this->context().camera;
  const auto camera_step = 20.f;

	// get light references
  auto& sunlight = this->lights[ 0 ];
  auto& spotlight = this->lights[ 1 ];

  // if the mouse is moved at all
  if (what.type == sf::Event::MouseMoved)
  {
    // get the current position of the mouse in the window
    sf::Vector2i localPosition = sf::Mouse::getPosition(window);

    // subtract the last known mouse position from the current position
    int mouseX = localPosition.x - mousePos.x;
    int mouseY = localPosition.y - mousePos.y;

    // move the camera by a factore of how much the mouse moved
    context().camera->offsetOrientation(mouseSensitivity * mouseY, mouseSensitivity * mouseX);

    if (mouseX != 0 || mouseY != 0)
    {
      // move the mouse to the center of the screen, this prevents running out of the window
      sf::Mouse::setPosition(sf::Vector2i(this->center().x, this->center().y), window);
      // set the mouse position to the current position 
      mousePos = sf::Vector2i(this->center().x, this->center().y);
    }
  }    // MouseMove

	if (what.type == sf::Event::KeyReleased){
    switch (what.key.code) {
    case sf::Keyboard::T:	// toggle the sun
      sunlight.enabled = !sunlight.enabled;
      break;
    case sf::Keyboard::F:    // Toggle spot light
      spotlight.enabled = !spotlight.enabled;
      break;
    case sf::Keyboard::M:	// Toggle shadow mapping
		this->_shadowmapping_enabled = !this->_shadowmapping_enabled;
      break;
	case sf::Keyboard::R:	// debug quad
		this->_render_debug_quad = !this->_render_debug_quad;
		break;
    };    // switch
	}

  if (what.type == sf::Event::KeyReleased)
  {

    if (what.key.code == sf::Keyboard::P) // Drop a block
    {
      vec3 camDir = camera.forward();

      // Move the camera forwards
      camera.offsetPosition(camera_step * vec3(camDir.x, 0, camDir.z));

      // add a block to the center of the world
      auto& b = this->add_child<Block>(new Block(this->center()));
      auto bpos = b.position();

      // move the block to the position of the camera
      vec3 camPos = camera.getPosition();
      bpos.x = camPos.x;
      bpos.z = camPos.z;
      b.position(bpos);

      // Move the camera backwards
      camera.offsetPosition(camera_step * vec3(-camDir.x, 0, -camDir.z));
    }
  }

	// always update spotlight position based on camera
	spotlight.direction = this->context().camera->forward();
	spotlight.position = position_type( this->context().camera->getPosition() );
	spotlight.position.y -= 5.f;	// move down from eye level to better resemble a flashlight

	Object::handle_event();// forward to base method
}    // dispatch
Пример #12
0
void DefRenderer::Init()
{
	nullProg = new ShaderProgram(SHADER_PATH + "nullVS.glsl", SHADER_PATH + "nullFS.glsl");
	nullProg->BindAttribLoc(0, "Position");
	nullProg->Link();
	ivec2 screen = Graphics::GetViewport();

	glGenFramebuffers(1, &fbo);
	GLuint FBOtexture[TEXTURES]; //color, normal
	glGenTextures(TEXTURES, FBOtexture);
	glGenRenderbuffers(1, &rbo); //depth & stencil
	CHECK_GL_ERROR();

	glBindFramebuffer(GL_FRAMEBUFFER, fbo);

	//initialization of the textures and buffers
	for (int i = 0; i < TEXTURES; i++)
	{
		glBindTexture(GL_TEXTURE_2D, FBOtexture[i]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, screen.x, screen.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
		textures[i] = new Texture(FBOtexture[i]);
	}
	glBindRenderbuffer(GL_RENDERBUFFER, rbo);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL, screen.x, screen.y);
	CHECK_GL_ERROR();

	//configuring frame buffer
	//setting texture attachments
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, FBOtexture[0], 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, FBOtexture[1], 0);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo);
	CHECK_GL_ERROR();

	//marking that frag shader will render to the 2 bound textures
	//depth is handled in a different pipeline stage - no need to bother about it
	GLenum bufferToDraw[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
	glDrawBuffers(TEXTURES, bufferToDraw);
	CHECK_GL_ERROR();

	//check if we succeeded
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
		printf("Error - Framebuffer incomplete!\n");

	//now create all the required resources for rendering the screen quad
	vector<Vertex> *verts = new vector<Vertex>();
	verts->push_back(Vertex(vec3(-1.f, -1.f, 0)));
	verts->push_back(Vertex(vec3(1.f, -1.f, 0)));
	verts->push_back(Vertex(vec3(-1.f, 1.f, 0)));
	verts->push_back(Vertex(vec3(1.f, 1.f, 0)));

	model = new Model();
	model->SetVertices(verts, GL_STATIC_DRAW, true);
	model->FlushBuffers();
	model->SetUpAttrib(0, 2, GL_FLOAT, 0); //vec2 position

	program = new ShaderProgram(SHADER_PATH + "postProcVS.glsl", SHADER_PATH + "defRendFS.glsl");
	program->BindAttribLoc(0, "vertexPosition");
	program->Link();

	renderer = new Renderer();
	for (int i = 0; i < TEXTURES; i++)
		renderer->AddTexture(textures[i]);
	renderer->SetModel(model, GL_TRIANGLE_FAN);
	renderer->SetShaderProgram(program);
}
Пример #13
0
#include "DefRenderer.h"
#include "Graphics.h"
#include "GameObject.h"

GLuint DefRenderer::fbo;
GLuint DefRenderer::rbo;
Texture* DefRenderer::textures[3];
Model* DefRenderer::model;
ShaderProgram* DefRenderer::program;
ShaderProgram* DefRenderer::nullProg;
Renderer* DefRenderer::renderer;
vec3 DefRenderer::sunDir = vec3(0, -1, 0);
vec3 DefRenderer::sunColor = vec3(0.5f, 0.5f, 0.5f);

#define TEXTURES 2

void DefRenderer::Init()
{
	nullProg = new ShaderProgram(SHADER_PATH + "nullVS.glsl", SHADER_PATH + "nullFS.glsl");
	nullProg->BindAttribLoc(0, "Position");
	nullProg->Link();
	ivec2 screen = Graphics::GetViewport();

	glGenFramebuffers(1, &fbo);
	GLuint FBOtexture[TEXTURES]; //color, normal
	glGenTextures(TEXTURES, FBOtexture);
	glGenRenderbuffers(1, &rbo); //depth & stencil
	CHECK_GL_ERROR();

	glBindFramebuffer(GL_FRAMEBUFFER, fbo);
Пример #14
0
Ray PointLight::GenerateRay(const vec3 &HitPoint, float *t){
	vec3 direction = vec3(position - HitPoint);
	*t = length(direction);
	return Ray(normalize(direction), HitPoint, 0.0f, *t);
}
Пример #15
0
bool
plane::
closestPtIn ( vec3& dest, ValueType xval, ValueType yval, ValueType zval ) const
{
	return closestPtIn ( dest, vec3 ( xval, yval, zval ) );
}
Пример #16
0
Box::Box(glm::vec3 size, glm::vec4 color,
         glm::vec3 pos, bool haveNormals)
{


    std::vector<vec3> vertex = {
        vec3(-0.5f, -0.5f, -0.5f),
        vec3(-0.5f,  0.5f, -0.5f),
        vec3( 0.5f,  0.5f, -0.5f),
        vec3( 0.5f,  0.5f, -0.5f),
        vec3( 0.5f, -0.5f, -0.5f),
        vec3(-0.5f, -0.5f, -0.5f),

        vec3(-0.5f, -0.5f,  0.5f),
        vec3( 0.5f, -0.5f,  0.5f),
        vec3( 0.5f,  0.5f,  0.5f),
        vec3( 0.5f,  0.5f,  0.5f),
        vec3(-0.5f,  0.5f,  0.5f),
        vec3(-0.5f, -0.5f,  0.5f),

        vec3(-0.5f,  0.5f,  0.5f),
        vec3(-0.5f,  0.5f, -0.5f),
        vec3(-0.5f, -0.5f, -0.5f),
        vec3(-0.5f, -0.5f, -0.5f),
        vec3(-0.5f, -0.5f,  0.5f),
        vec3(-0.5f,  0.5f,  0.5f),

        vec3( 0.5f,  0.5f,  0.5f),
        vec3( 0.5f, -0.5f,  0.5f),
        vec3( 0.5f, -0.5f, -0.5f),
        vec3( 0.5f, -0.5f, -0.5f),
        vec3( 0.5f,  0.5f, -0.5f),
        vec3( 0.5f,  0.5f,  0.5f),

        vec3(-0.5f, -0.5f, -0.5f),
        vec3( 0.5f, -0.5f, -0.5f),
        vec3( 0.5f, -0.5f,  0.5f),
        vec3( 0.5f, -0.5f,  0.5f),
        vec3(-0.5f, -0.5f,  0.5f),
        vec3(-0.5f, -0.5f, -0.5f),

        vec3(-0.5f,  0.5f, -0.5f),
        vec3(-0.5f,  0.5f,  0.5f),
        vec3( 0.5f,  0.5f,  0.5f),
        vec3( 0.5f,  0.5f,  0.5f),
        vec3( 0.5f,  0.5f, -0.5f),
        vec3(-0.5f,  0.5f, -0.5f)
    };

    std::vector<vec3> normals = {
        vec3(0.0f,  0.0f, -1.0f),
        vec3(0.0f,  0.0f, -1.0f),
        vec3(0.0f,  0.0f, -1.0f),
        vec3(0.0f,  0.0f, -1.0f),
        vec3(0.0f,  0.0f, -1.0f),
        vec3(0.0f,  0.0f, -1.0f),

        vec3(0.0f,  0.0f,  1.0f),
        vec3(0.0f,  0.0f,  1.0f),
        vec3(0.0f,  0.0f,  1.0f),
        vec3(0.0f,  0.0f,  1.0f),
        vec3(0.0f,  0.0f,  1.0f),
        vec3(0.0f,  0.0f,  1.0f),

        vec3(-1.0f,  0.0f,  0.0f),
        vec3(-1.0f,  0.0f,  0.0f),
        vec3(-1.0f,  0.0f,  0.0f),
        vec3(-1.0f,  0.0f,  0.0f),
        vec3(-1.0f,  0.0f,  0.0f),
        vec3(-1.0f,  0.0f,  0.0f),

        vec3(1.0f,  0.0f,  0.0f),
        vec3(1.0f,  0.0f,  0.0f),
        vec3(1.0f,  0.0f,  0.0f),
        vec3(1.0f,  0.0f,  0.0f),
        vec3(1.0f,  0.0f,  0.0f),
        vec3(1.0f,  0.0f,  0.0f),

        vec3(0.0f,  -1.0f,  0.0f),
        vec3(0.0f,  -1.0f,  0.0f),
        vec3(0.0f,  -1.0f,  0.0f),
        vec3(0.0f,  -1.0f,  0.0f),
        vec3(0.0f,  -1.0f,  0.0f),
        vec3(0.0f,  -1.0f,  0.0f),

        vec3(0.0f,  1.0f,  0.0f),
        vec3(0.0f,  1.0f,  0.0f),
        vec3(0.0f,  1.0f,  0.0f),
        vec3(0.0f,  1.0f,  0.0f),
        vec3(0.0f,  1.0f,  0.0f),
        vec3(0.0f,  1.0f,  0.0f),





    };


    std::vector<GLuint> elements;
//    for(int i = 0; i < vertex.size(); ++i)
//        elements.push_back(i);

    for(int i = 0; i < vertex.size(); ++i)
        m_color.push_back(color);

    this->m_transform->translate(pos);

    m_transform->scale(size);

    if(haveNormals)
        setGlThings(vertex,elements,normals);
    else
        setGlThings(vertex,elements,std::vector<vec3>(),false);


}
void SSAO::BuildFrustumCorner() {
	_frustumCorner = vec3(0,0,0);
	_frustumCorner.y = tanf(_fov / 2.0f) * _far;
	_frustumCorner.x = _frustumCorner.y * float(_screenWidth) / float(_screenHeight);
	_frustumCorner.z = _far;
}
Пример #18
0
void IterateVoxel(inout vec3 voxel, Ray ray, inout vec4 colorAccum)
{
	float maxX = 0.0;
	float maxY = 0.0;
	float maxZ = 0.0;
	
		
	if(ray.Direction.x != 0.0)
	{
		maxX = max((voxel.x - ray.Origin.x) / ray.Direction.x, (voxel.x + 1.0 - ray.Origin.x) / ray.Direction.x);
	}
	if(ray.Direction.y != 0.0)
	{
		maxY = max((voxel.y - ray.Origin.y) / ray.Direction.y, (voxel.y + 1.0 - ray.Origin.y) / ray.Direction.y);
	}
	if(ray.Direction.z != 0.0)
	{
		maxZ = max((voxel.z - ray.Origin.z) / ray.Direction.z, (voxel.z + 1.0 - ray.Origin.z) / ray.Direction.z);
	}

	vec2 hitPoint;
	float texture;
	if(maxX <= min(maxY, maxZ))
	{
		voxel.x += sign(ray.Direction.x);
		int block = GetVoxel(voxel);

		if(block != 0)
		{
			texture = (ray.Direction.x > 0) ? textureFaces[block*6 + 0] : textureFaces[block*6 + 1];
			hitPoint = fract(ray.Origin + ray.Direction * maxX).zy;
			colorAccum = texture2DArray(textures, vec3(1.0 - abs(hitPoint), texture));
			colorAccum.xyz *= 0.9;
		}
	}
	if(maxY <= min(maxX, maxZ))
	{
		voxel.y += sign(ray.Direction.y);
		int block = GetVoxel(voxel);

		if(block != 0)
		{
			texture = (ray.Direction.y > 0) ? textureFaces[block*6 + 3] : textureFaces[block*6 + 2];
			hitPoint = fract(ray.Origin + ray.Direction * maxY).xz;
			colorAccum = texture2DArray(textures, vec3(1.0 - abs(hitPoint), texture));
			colorAccum.xyz *= 1.0;
		}
	}
	if(maxZ <= min(maxX, maxY))
	{
		voxel.z += sign(ray.Direction.z);
		int block = GetVoxel(voxel);

		if(block != 0)
		{
			texture = (ray.Direction.z > 0) ? textureFaces[block*6 + 4] : textureFaces[block*6 + 5];
			hitPoint = fract(ray.Origin + ray.Direction * maxZ).xy;
			colorAccum = texture2DArray(textures, vec3(1.0 - abs(hitPoint), texture));
			colorAccum.xyz *= 0.8;
		}
	}
}
Пример #19
0
bool TextureManager::LoadTexture(const char* filename, const unsigned int texID, GLenum image_format, GLint internal_format, GLint level, GLint border)
{
	//image format
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	//pointer to the image, once loaded
	FIBITMAP *dib(0);
	//pointer to the image data
	BYTE* bits(0);
	//image width and height
	unsigned int width(0), height(0);
	//OpenGL's image ID to map to
	GLuint gl_texID;
	
	//check the file signature and deduce its format
	fif = FreeImage_GetFileType(filename, 0);
	//if still unknown, try to guess the file format from the file extension
	if(fif == FIF_UNKNOWN) 
		fif = FreeImage_GetFIFFromFilename(filename);
	//if still unkown, return failure
	if(fif == FIF_UNKNOWN)
		return false;

	//check that the plugin has reading capabilities and load the file
	if(FreeImage_FIFSupportsReading(fif))
		dib = FreeImage_Load(fif, filename);
	//if the image failed to load, return failure
	if(!dib)
		return false;

	//retrieve the image data
	bits = FreeImage_GetBits(dib);
	//get the image width and height
	width = FreeImage_GetWidth(dib);
	height = FreeImage_GetHeight(dib);
	//if this somehow one of these failed (they shouldn't), return failure
	if((bits == 0) || (width == 0) || (height == 0))
		return false;
	
	//if this texture ID is in use, unload the current texture
	if(m_texID.find(texID) != m_texID.end())
		glDeleteTextures(1, &(m_texID[texID]));

	cout << "(" << width << "," << height << ")" << endl;
	//compute vertex and normals
	vector<vec3> vertices;
	vector<vec3> normals;
	float scale = 0.05f;
	for (int i = 0; i < width -1; i++){
		for (int j = 0; j < height-1; j++){
			// four corners' vertex
			//t1
			//vec3 v00t1(i, bits[mat2vecIndex(i, j, width)] / 255.0f * scale, j); // x, height, z
			//vec3 v10t1(i + 1, bits[mat2vecIndex(i + 1, j, width)] / 255.0f* scale, j); // x, height, z
			//vec3 v11t1(i + 1, bits[mat2vecIndex(i + 1, j + 1, width)] / 255.0f* scale, j + 1); // x, height, z
			////t2
			//vec3 v11t2(i + 1, bits[mat2vecIndex(i + 1, j + 1, width)] / 255.0f* scale, j + 1); // x, height, z
			//vec3 v01t2(i, bits[mat2vecIndex(i, j + 1, width)] / 255.0f* scale, j + 1); // x, height, z
			//vec3 v00t2(i, bits[mat2vecIndex(i, j, width)] / 255.0f* scale, j); // x, height, z
			float fi = (float) i;
			float fj = (float) j;
			vec3 v00t1 = vec3(fi, 0, fj) * scale; // x, height, z
			vec3 v10t1 = vec3(fi + 1, 0, fj) * scale; // x, height, z
			vec3 v11t1 = vec3(fi + 1, 0, fj + 1) * scale; // x, height, z
			//t2
			vec3 v11t2 = vec3(fi, 0, fj + 1) * scale; // x, height, z
			vec3 v01t2 = vec3(fi, 0, fj + 1) * scale; // x, height, z			
			vec3 v00t2 = vec3(fi, 0, fj) * scale; // x, height, z			
			

			vec3 n1 = glm::normalize(cross(v00t1 - v10t1, v00t1 - v11t1));
			vec3 n2 = glm::normalize(cross(v01t2 - v00t2, v01t2 - v11t2));
			//t1
			vertices.push_back(v00t1);
			vertices.push_back(v10t1);
			vertices.push_back(v11t1);
			//t2
			vertices.push_back(v11t2);
			vertices.push_back(v01t2);
			vertices.push_back(v00t2);

			normals.push_back(n1);
			normals.push_back(n2);
		}
	}

	hmap.normals = normals;
	hmap.vertices = vertices;
	hmap.w = width;
	hmap.h = height;

	cout << "vertexes: " << vertices.size() << endl;
	cout << "triangles/normals: " << normals.size() << endl;

	//generate an OpenGL texture ID for this texture
	glGenTextures(1, &gl_texID);
	//store the texture ID mapping
	m_texID[texID] = gl_texID;
	//bind to the new texture ID
	glBindTexture(GL_TEXTURE_2D, gl_texID);

	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_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	//store the texture data for OpenGL use
	glTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height,
		border, image_format, GL_UNSIGNED_BYTE, bits);

	//Free FreeImage's copy of the data
	FreeImage_Unload(dib);

	//return success
	return true;
}
Пример #20
0
void templateAppDraw(void) {

    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    gfx->set_matrix_mode(MODELVIEW_MATRIX);
    gfx->load_identity();

    if (view_delta->x || view_delta->y) {
        if (view_delta->y) next_rotz -= view_delta->y;

        if (view_delta->x) {
            next_rotx -= view_delta->x;
            next_rotx = CLAMP(next_rotx, 0.0f, 90.0f);
        }

        view_delta->x =
        view_delta->y = 0.0f;
    }

    rotx = rotx * 0.9f + next_rotx * 0.1f;
    rotz = rotz * 0.9f + next_rotz * 0.1f;

    eye->x = center->x +
             distance *
             cosf(rotx * DEG_TO_RAD) *
             sinf(rotz * DEG_TO_RAD);

    eye->y = center->y -
             distance *
             cosf(rotx * DEG_TO_RAD) *
             cosf(rotz * DEG_TO_RAD);

    eye->z = center->z +
             distance *
             sinf(rotx * DEG_TO_RAD);

    rotx = rotx * 0.9f + next_rotx * 0.1f;
    rotz = rotz * 0.9f + next_rotz * 0.1f;

    center = maze->location;

    gfx->look_at(eye,
                 center,
                 up);

    if (double_tap) {
        /* Variable to hold the 3D location on the far plane of the frustum. */
        vec3 location;
        /* This function converts a 2D point from the screen coordinates
         * to a 3D point in space.  The return value is true or false, depending on
         * whether or not the query is successful.  It's a GFX helper, but built
         * basically the same way as the standard gluUnproject
         * (http://www.opengl.org/sdk/docs/man/xhtml/gluUnproject.xml)
         * function.
         */
        if (gfx->unproject(view_location->x,
                           /* The origin of the OpenGLES color buffer is down
                            * left, but its location for iOS and Android is up
                            * left.  To handle this situation, simply use the
                            * viewport matrix height data (viewport_matrix[3])
                            * to readjust the Y location of the picking point
                            * onscreen.
                            */
                           viewport_matrix[3] - view_location->y,
                           /* This parameter represents the depth that you want
                            * to query, with 1 representing the far clipping
                            * plane and 0 representing the near clipping plane.
                            * In this case, you are only interested in the far
                            * clipping plane value, which explains the value 1.
                            */
                           1.0f,
                           gfx->get_modelview_matrix(),
                           gfx->get_projection_matrix(),
                           viewport_matrix,
                           location)) {

            /* Now that you have the XYZ location on the far plane, you can
             * create the collision ray.  Begin by creating the starting point,
             * which is basically the current camera eye position.
             */
            btVector3 ray_from(eye->x,
                               eye->y,
                               eye->z),
            /* Translate the resulting location of GFX::unproject based on the
             * current eye location to make sure that the coordinate system
             * will fit with what the player currently sees onscreen.
             */
            ray_to(location->x + eye->x,
                   location->y + eye->y,
                   location->z + eye->z);
            /* Create the collision ray. */
            btCollisionWorld::ClosestRayResultCallback collision_ray(ray_from,
                                                                     ray_to);
            /* Launch the ray in space. */
            dynamicsworld->rayTest(ray_from,
                                   ray_to,
                                   collision_ray);
            /* Check if the collision ray gets a hit, and check if the
             * collision object involved is the maze btRigidBody.
             */
            if (collision_ray.hasHit() &&
                collision_ray.m_collisionObject == maze->btrigidbody) {

                collision_ray.m_hitNormalWorld.normalize();
                /* Check if the normal Z is pointing upward to make sure
                 * the hit is on the floor of the maze.
                 */
                if (collision_ray.m_hitNormalWorld.z() == 1.0f) {
                    /* Since you got a valid hit, it is time to create the
                     * pathfinding query to send to Detour.  First, assign
                     * the current player location as the starting point of
                     * the query.
                     */
                    navigationpath_player.start_location = player->location;
                    /* Then simply use the collision ray hit position XYZ as
                     * the end point of the path query.
                     */
                    navigationpath_player.end_location->x = collision_ray.m_hitPointWorld.x();
                    navigationpath_player.end_location->y = collision_ray.m_hitPointWorld.y();
                    navigationpath_player.end_location->z = collision_ray.m_hitPointWorld.z();
                    /* The query is ready to be sent to Detour, so send it over.
                     * If Detour was able to find a path, the function will
                     * return 1 and will store the way points information
                     * inside the navigationpathdata_player variable; othewise
                     * the function will return 0.
                     */
                    if (navigation->get_path(&navigationpath_player,
                                             &navigationpathdata_player)) {
                        player_next_point = 1;

                        /* Loop while you've got some way points.  Please note
                         * that by default, the function will assign the number
                         * of path_point_count to be the way points returned by
                         * Detour.  However, the function implementation added
                         * another point which is the exact same end location
                         * that you specified in your query.  The reason is
                         * that, most of the time, the ending point not exactly
                         * on the mavigation mesh, so the library will return
                         * the closest pont.  Depending on what you want to
                         * achieve, you may or may not want to use this extra
                         * way point.  But for this tutorial, you are going to
                         * take it into consideration.
                         */
                        for (int i=0; i!=navigationpathdata_player.path_point_count + 1; ++i)
                            console_print("%d: %f %f %f\n",
                                          i,
                                          navigationpathdata_player.path_point_array[i]->x,
                                          navigationpathdata_player.path_point_array[i]->y,
                                          navigationpathdata_player.path_point_array[i]->z);
                        printf("\n");
                    }
                }
            }
        }
        
        double_tap = 0;
    }
    
    if (navigationpathdata_player.path_point_count) {
        move_entity(player,                     // The player OBJMESH pointer.
                    &navigationpathdata_player, // The player navigation path
                                                // structure.
                    &player_next_point,         // The way point the player is
                                                // moving towards.
                    3.0f);                      // The speed to use as factor
                                                // to the linear velocity of
                                                // the btRigidBody.
    }

    program->draw();

    glUniform1i(program->get_uniform_location(TM_Diffuse_String), TM_Diffuse);

    for (auto objmesh=obj->objmesh.begin();
         objmesh!=obj->objmesh.end(); ++objmesh) {

        gfx->push_matrix();

        mat4 mat;

        objmesh->btrigidbody->getWorldTransform().getOpenGLMatrix(mat.m());

        objmesh->location = vec3(mat[3], true);

        gfx->multiply_matrix(mat);

        glUniformMatrix4fv(program->get_uniform_location((char *)"MODELVIEWPROJECTIONMATRIX"),
                           1,
                           GL_FALSE,
                           gfx->get_modelview_projection_matrix().m());

        objmesh->draw();

        gfx->pop_matrix();
    }
    
    navigation->draw(gfx);
    
    dynamicsworld->stepSimulation(1.0f / 60.0f);
}
Пример #21
0
vec3 Matrix44::up()
{
    return vec3(m_data[4], m_data[5], m_data[6]);
}
Пример #22
0
float Trans_Mesh::Ray_Tri_Intersect(const vec3& rayorig, const vec3& raydir)  {

	Batch* cone_batch = Batches[0];
	Batch* rod_batch = Batches[1];

	mat4 bvtrans, bvaxis, rodscale, rodtrans, world;
	const float offaxis =10.0f;
	rodscale.setupScale(offaxis/3.0f, .1f, .1f);
	const float distaway = 120.0f;
	vec3 transpost =  GetPosition()-LastCamPosition;
	transpost.normalize();

	//FIRST AXIS.. RED AND X
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+vec3(offaxis, 0.0f, 0.0f));
	bvaxis.setupTranslation(vec3(-1.0f, 0, 0));
	world = bvaxis*bvtrans;
	float dist = Ray_Tri_Intersect(rayorig, raydir, world, cone_batch->StartIndex, cone_batch->NumIndices);
	if(dist != INFINITY) {
		HitAxis= vec3(1.0, 0.0f, 0.0f);
		return dist;
	}
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition);
	rodtrans.setupTranslation(vec3(1.3f, 0, 0));
	world = rodtrans*rodscale*bvtrans;
	dist = Ray_Tri_Intersect(rayorig, raydir, world, rod_batch->StartIndex, rod_batch->NumIndices);
	if(dist != INFINITY) {
		HitAxis=vec3(1.0, 0.0f, 0.0f);
		return dist;
	}

	//SECOND AXIS. .. BLUE AND Z
	mat4 rot;
	rot.setupRotateY(-Pi/2.0f);

	bvaxis.setupTranslation( 0.0f,  0.0f, -1.0f);
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+ vec3(0.0f, 0.0f, offaxis));

	world = bvaxis*rot*bvtrans;
	dist = Ray_Tri_Intersect(rayorig, raydir, world, cone_batch->StartIndex, cone_batch->NumIndices);
	if(dist != INFINITY) {
		HitAxis= vec3(0.0, 0.0f, 1.0f);
		return dist;
	}
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+ vec3(1.0f, 0, offaxis/2.0f));
	world  = rodscale*rot*bvtrans;
	dist = Ray_Tri_Intersect(rayorig, raydir, world, rod_batch->StartIndex, rod_batch->NumIndices);
	if(dist != INFINITY) {
		HitAxis=vec3(0.0, 0.0f, 1.0f);
		return dist;
	}

	//THIRD AXIS . . . . GREEEN AND Y
	rot.setupRotateZ(Pi/2.0f);
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition + vec3(0.0f, offaxis, 0.0f));
	bvaxis.setupTranslation(0.0f, -1.0f, 0.0f);

	world= bvaxis*rot*bvtrans;
	dist = Ray_Tri_Intersect(rayorig, raydir, world, cone_batch->StartIndex, cone_batch->NumIndices);
	if(dist != INFINITY) {
		HitAxis=vec3(0.0, 1.0f, 0.0f);
		return dist;
	}
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+ vec3(1.0f, offaxis/2.0f, 0.0f));
	rodtrans.setupTranslation(vec3(0,  1.3f, 0));
	world = rodtrans*rodscale*rot*bvtrans;
	dist = Ray_Tri_Intersect(rayorig, raydir, world, cone_batch->StartIndex, cone_batch->NumIndices);
	if(dist != INFINITY) {
		HitAxis=vec3(0.0, 1.0f, 0.0f);
		return dist;
	}
	return dist;
}
Пример #23
0
vec3 Matrix44::right()
{
	return vec3(m_data[0], m_data[1], m_data[2]);
}
Пример #24
0
void Trans_Mesh::Draw(const Base_Camera* camera, float dt){

	Graphics::SetTopology(PRIM_TRIANGLELIST);
	Graphics::DepthStates::NoDepthTest.Bind();
	Graphics::RasterizerStates::CullNone.Bind();
	Graphics::BlendStates::No_Blend.Bind();

	VB[0].BindAsVertexBuffer();
	IB.BindAsIndexBuffer();

	// first axis
	Batch* cone_batch = Batches[0];
	Batch* rod_batch = Batches[1];

	struct tempstruct{
		mat4 vp;
		vec4 color;
	};
	tempstruct t;
	mat4 bvtrans, bvaxis, rodscale, rodtrans;

	const float offaxis =10.0f;
	rodscale.setupScale(offaxis/3.0f, .1f, .1f);
	const float distaway = 120.0f;
	LastCamPosition = camera->Position;

	vec3 transpost =  GetPosition()-LastCamPosition;
	transpost.normalize();

	//FIRST AXIS.. RED AND X
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+vec3(offaxis, 0.0f, 0.0f));
	bvaxis.setupTranslation(vec3(-1.0f, 0, 0));
	t.vp = bvaxis*bvtrans*camera->VP;// we have to move the BV that was pregenerated into the correct position and scale it 
	t.vp.Transpose();
	t.color = vec4(XAxis_Color, 1);//red  ==x
	CBuffer0.Update(&t);

	cone_batch->GetVS()->Bind();
	cone_batch->GetVS()->SetConstantBuffer(CBuffer0, 0);
	cone_batch->GetPS()->Bind();

	Graphics::DrawIndexed(cone_batch->StartIndex, cone_batch->NumIndices);
	//now draw the rod
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition);
	rodtrans.setupTranslation(vec3(1.3f, 0, 0));
	t.vp = rodtrans*rodscale*bvtrans*camera->VP;// we have to move the BV that was pregenerated into the correct position and scale it 
	t.vp.Transpose();
	CBuffer0.Update(&t);

	cone_batch->GetVS()->SetConstantBuffer(CBuffer0, 0);
	Graphics::DrawIndexed(rod_batch->StartIndex, rod_batch->NumIndices);


	//SECOND AXIS. .. BLUE AND Z
	mat4 rot;
	rot.setupRotateY(-Pi/2.0f);
	bvaxis.setupTranslation( 0.0f,  0.0f, -1.0f);
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+ vec3(0.0f, 0.0f, offaxis));

	t.vp = bvaxis*rot*bvtrans*camera->VP;
	t.vp.Transpose();
	t.color = vec4(ZAxis_Color, 1);
	CBuffer0.Update(&t);
	cone_batch->GetVS()->SetConstantBuffer(CBuffer0, 0);

	Graphics::DrawIndexed(cone_batch->StartIndex, cone_batch->NumIndices);

	//now draw the rod
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+ vec3(1.0f, 0, offaxis/2.0f));
	t.vp = rodscale*rot*bvtrans*camera->VP;// we have to move the BV that was pregenerated into the correct position and scale it 
	t.vp.Transpose();
	CBuffer0.Update(&t);

	cone_batch->GetVS()->SetConstantBuffer(CBuffer0, 0);
	Graphics::DrawIndexed(rod_batch->StartIndex, rod_batch->NumIndices);

	//THIRD AXIS . . . . GREEN AND Y
	rot.setupRotateZ(Pi/2.0f);
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition + vec3(0.0f, offaxis, 0.0f));
	bvaxis.setupTranslation(0.0f, -1.0f, 0.0f);

	t.vp = bvaxis*rot*bvtrans*camera->VP;
	t.vp.Transpose();
	t.color = vec4(YAxis_Color, 1);
	CBuffer0.Update(&t);
	cone_batch->GetVS()->SetConstantBuffer(CBuffer0, 0);

	Graphics::DrawIndexed(cone_batch->StartIndex, cone_batch->NumIndices);

	//now draw the rod
	bvtrans.setupTranslation((transpost*distaway) + LastCamPosition+ vec3(1.0f, offaxis/2.0f, 0.0f));
	rodtrans.setupTranslation(vec3(0,  1.3f, 0));
	t.vp = rodtrans*rodscale*rot*bvtrans*camera->VP;// we have to move the BV that was pregenerated into the correct position and scale it 
	t.vp.Transpose();
	CBuffer0.Update(&t);

	cone_batch->GetVS()->SetConstantBuffer(CBuffer0, 0);
	Graphics::DrawIndexed(rod_batch->StartIndex, rod_batch->NumIndices);
}
Пример #25
0
void CKillMessages::OnRender()
{
	if (!g_Config.m_ClShowKillMessages)
		return;

	float Width = 400*3.0f*Graphics()->ScreenAspect();
	float Height = 400*3.0f;

	Graphics()->MapScreen(0, 0, Width*1.5f, Height*1.5f);
	float StartX = Width*1.5f-10.0f;
	float y = 30.0f; //XXX was 20.0f

	for(int i = 1; i <= MAX_KILLMSGS; i++)
	{
		int r = (m_KillmsgCurrent+i)%MAX_KILLMSGS;
		if(Client()->GameTick() > m_aKillmsgs[r].m_Tick+50*10)
			continue;

		float FontSize = 36.0f;
		float KillerNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aKillerName, -1);
		float VictimNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aVictimName, -1);

		float x = StartX;

		// render victim name
		x -= VictimNameW;
		if(m_aKillmsgs[r].m_VictimID >= 0 && g_Config.m_ClChatTeamColors && m_aKillmsgs[r].m_VictimDDTeam)
		{
			vec3 rgb = HslToRgb(vec3(m_aKillmsgs[r].m_VictimDDTeam / 64.0f, 1.0f, 0.75f));
			TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0);
		}
		TextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aVictimName, -1);
		TextRender()->TextColor(1.0, 1.0, 1.0, 1.0);

		// render victim tee
		x -= 24.0f;

		if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS)
		{
			if(m_aKillmsgs[r].m_ModeSpecial&1)
			{
				Graphics()->BlendNormal();
				Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
				Graphics()->QuadsBegin();

				if(m_aKillmsgs[r].m_VictimTeam == TEAM_RED)
					RenderTools()->SelectSprite(SPRITE_FLAG_BLUE);
				else
					RenderTools()->SelectSprite(SPRITE_FLAG_RED);

				float Size = 56.0f;
				IGraphics::CQuadItem QuadItem(x, y-16, Size/2, Size);
				Graphics()->QuadsDrawTL(&QuadItem, 1);
				Graphics()->QuadsEnd();
			}
		}

		RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_VictimRenderInfo, EMOTE_PAIN, vec2(-1,0), vec2(x, y+28));
		x -= 32.0f;

		// render weapon
		x -= 44.0f;
		if (m_aKillmsgs[r].m_Weapon >= 0)
		{
			Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
			Graphics()->QuadsBegin();
			RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[m_aKillmsgs[r].m_Weapon].m_pSpriteBody);
			RenderTools()->DrawSprite(x, y+28, 96);
			Graphics()->QuadsEnd();
		}
		x -= 52.0f;

		if(m_aKillmsgs[r].m_VictimID != m_aKillmsgs[r].m_KillerID)
		{
			if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS)
			{
				if(m_aKillmsgs[r].m_ModeSpecial&2)
				{
					Graphics()->BlendNormal();
					Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
					Graphics()->QuadsBegin();

					if(m_aKillmsgs[r].m_KillerTeam == TEAM_RED)
						RenderTools()->SelectSprite(SPRITE_FLAG_BLUE, SPRITE_FLAG_FLIP_X);
					else
						RenderTools()->SelectSprite(SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X);

					float Size = 56.0f;
					IGraphics::CQuadItem QuadItem(x-56, y-16, Size/2, Size);
					Graphics()->QuadsDrawTL(&QuadItem, 1);
					Graphics()->QuadsEnd();
				}
			}

			// render killer tee
			x -= 24.0f;
			RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_KillerRenderInfo, EMOTE_ANGRY, vec2(1,0), vec2(x, y+28));
			x -= 32.0f;

			// render killer name
			x -= KillerNameW;
			TextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aKillerName, -1);
		}

		y += 46.0f;
	}
}
Пример #26
0
bool Trans_Mesh::Init(){
	XAxis_Color=vec3(1, 0, 0);
	YAxis_Color=vec3(0, 1,0);
	ZAxis_Color=vec3(0, 0, 1);
	Hit_Axis_Color = vec3(1, 1, 1);
	HitAxis = vec3(0,0,0);
	Vertices.push_back(vec3(1.0f, 0.0f, 0.0f));
	const float split=16.0f;
	//note: all of these shapes will have to be scaled to correctly in the draw function, but its not something the user will do. that will be done in the draw function below
	// first create the cone pointer
	uint16_t index=1;
	for(float i=0.0f; i<2*Pi; i+=Pi/split){
		vec3 p;
		p.x=-1.0f;
		p.y=sinf(i);
		p.z=cosf(i);
		Vertices.push_back(p);
	}

	index=0;
	for(float i=0.0f; i<2*Pi; i+=Pi/split){
		Indices.push_back(0);
		Indices.push_back(index+2);
		Indices.push_back(index+1);
		index+=1;
	}
	Indices[Indices.size()-2]=Vertices.size()-1;
	Indices.push_back(0);
	Indices.push_back(1);
	Indices.push_back(Vertices.size()-1);

	FormatDesc layers[1] = { FormatDesc(TYPE_VERTEX, FORMAT_FLOAT, 4, 0) };
	Batch* b = new Batch();
	b->GetVS()->CompileShaderFromMemory(Graphics::Shader_Defines::BV_VS);
	b->GetVS()->CreateInputLayout(layers, 1);
	b->GetPS()->CompileShaderFromMemory(Graphics::Shader_Defines::BV_PS);
	b->NumIndices = Indices.size();
	b->StartIndex =0;
	b->NumVerts = Vertices.size();
	Batches.push_back(b);

	index=Vertices.size();

	// now create the rod to connect to it 
	// a long triangle looks the same as a rod
	Vertices.push_back(vec3(1.0f, 1.0f, 0.0f));//0
	Vertices.push_back(vec3(1.0f, -1.0f, 1.0f));//1
	Vertices.push_back(vec3(1.0f, -1.0f, -1.0f));//2

	Vertices.push_back(vec3(-1.0f, 1.0f, 0.0f));//3
	Vertices.push_back(vec3(-1.0f, -1.0f, 1.0f));//4
	Vertices.push_back(vec3(-1.0f, -1.0f, -1.0f));//5

	Vertices.push_back(vec3(-1.0f, -1.0f, -1.0f));//extra vert is needed for alignment reasons.. .  i guess

	Batch* b1 = new Batch();
	b1->GetVS()->CompileShaderFromMemory(Graphics::Shader_Defines::BV_VS);
	b1->GetVS()->CreateInputLayout(layers, 1);
	b1->GetPS()->CompileShaderFromMemory(Graphics::Shader_Defines::BV_PS);
	b1->StartIndex =Indices.size();
	b1->NumVerts = 6;
	Batches.push_back(b1);

	Indices.push_back(index+0);
	Indices.push_back(index+4);
	Indices.push_back(index+3);

	Indices.push_back(index+1);
	Indices.push_back(index+4);
	Indices.push_back(index+0);

	Indices.push_back(index+1);
	Indices.push_back(index+4);
	Indices.push_back(index+2);

	Indices.push_back(index+2);
	Indices.push_back(index+4);
	Indices.push_back(index+5);

	Indices.push_back(index+5);
	Indices.push_back(index+2);
	Indices.push_back(index+3);

	Indices.push_back(index+3);
	Indices.push_back(index+2);
	Indices.push_back(index+0);

	b1->NumIndices = Indices.size()-b->NumIndices;


	CBuffer0.Create(1, sizeof(mat4) + sizeof(vec4), CONSTANT_BUFFER);
	VB[0].Create(Vertices.size(), sizeof(vec3), BufferType::VERTEX_BUFFER, DEFAULT, CPU_NONE, &Vertices[0]);
	IB.Create(Indices.size(), sizeof(uint16_t), BufferType::INDEX_BUFFER, DEFAULT, CPU_NONE, &Indices[0]);

	return true;
}
Пример #27
0
vec3 VoxelFile::get_max()
{
    return vec3(x_offset + x_size, y_offset + y_size, z_offset + z_size);
}
Пример #28
0
vec3 vec3::operator*(float v) const
{
	return vec3(x*v, y*v, z*v);
}
Пример #29
0
SeedPointGenerator::SeedPointGenerator()
    : Processor()
    , seedPoints_("seedPoints")
    , lineGroup_("line", "Line")
    , planeGroup_("plane", "Plane")
    , sphereGroup_("sphere", "Sphere")
    , numberOfPoints_("numberOfPoints", "Number of Points", 10, 1, 1000)
    , planeResolution_("planeResolution", "Resolution", vec2(4, 4), vec2(2, 2), vec2(100, 100))
    , planeOrigin_("planeOrigin_", "Origin", vec3(0.0f, 0.0f, 0.5f), vec3(-1, -1, -1),
                   vec3(1, 1, 1))
    , planeE1_("planeP1_", "Offset 1", vec3(1.0f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1))
    , planeE2_("planeP2_", "Offset 2", vec3(0.0f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1))
    , sphereCenter_("sphereCenter", "Center", vec3(0.5f, 0.5f, 0.5f), vec3(0, 0, 0), vec3(1, 1, 1))
    , sphereRadius_("sphereRadius", "Radius")
    , lineStart_("lineStart", "Start", vec3(0.5f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1))
    , lineEnd_("lineEnd_", "End", vec3(0.5f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1))
    , generator_("generator", "Generator")
    , randomness_("randomness", "Randomness")
    , useSameSeed_("useSameSeed", "Use same seed", true)
    , seed_("seed", "Seed", 1, 0, 1000)
    , rd_()
    , mt_(rd_()) {
    addPort(seedPoints_);

    generator_.addOption("random", "Random", RND);
    generator_.addOption("line", "Line", LINE);
    generator_.addOption("plane", "Plane", PLANE);
    generator_.addOption("sphere", "Sphere", SPHERE);
    generator_.setCurrentStateAsDefault();
    generator_.onChange(this, &SeedPointGenerator::onGeneratorChange);
    addProperty(generator_);

    lineGroup_.addProperty(lineStart_);
    lineGroup_.addProperty(lineEnd_);
    addProperty(lineGroup_);

    planeGroup_.addProperty(planeResolution_);
    planeGroup_.addProperty(planeOrigin_);
    planeGroup_.addProperty(planeE1_);
    planeGroup_.addProperty(planeE2_);
    addProperty(planeGroup_);

    sphereGroup_.addProperty(sphereCenter_);
    sphereGroup_.addProperty(sphereRadius_);
    sphereRadius_.set(vec2(0.45, 0.55));
    sphereRadius_.setCurrentStateAsDefault();
    addProperty(sphereGroup_);

    addProperty(numberOfPoints_);

    addProperty(randomness_);
    randomness_.addProperty(useSameSeed_);
    randomness_.addProperty(seed_);
    useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); });

    onGeneratorChange();
}
Пример #30
0
bool LoadAssimp( string file, vector <vec3> &vertices, vector <vec2> &uvs, vector <vec3> &normals, vector <GLuint> &indices ){
   /*
      Dane wyjściowe dla wierzchołków
   */
   vertices.clear();
   /*
      Dane wyjściowe dla UV Map
   */
   uvs.clear();
   /*
      Dane wyjściowe dla Normalnych
   */
   normals.clear();
   /*
      Dane wyjściowe dla kolejności trójkątów
   */
   indices.clear();
   /*
      Tworzenie importer dla ładowania danych.
   */
   Assimp::Importer importer;
   /*
      Wczytywanie pliku file (.obj)
   */
   const aiScene* scene = importer.ReadFile( file.c_str(), 0 );
   /*
      Sprawdzenie czy nie ma błedu.
   */
   if( !scene ){
      cout<<"importer.ReadFile ("<<file<<"):  "<<importer.GetErrorString()<<"\n";
      return false;
   }
   /*
      Wczytujemy tylko pierwszą część obiektu, inne pomijamy(występuje w obiektach kilku elementowych/częściowych).
   */
   const aiMesh* mesh = scene->mMeshes[0];
   unsigned int i = 0;
   /*
      Wektor dla pobierania danych.
   */
   aiVector3D tmp;
   //vertices:
   /*
      Wierzchołki obiektu.
   */
   vertices.reserve( mesh->mNumVertices );
   for( i = 0; i < mesh->mNumVertices; ++i ){
      tmp = mesh->mVertices[i];
      vertices.push_back( vec3( tmp.x, tmp.y, tmp.z ) );
   }
   //uvs:
   /*
      UV Mapy
   */
   uvs.reserve( mesh->mNumVertices );
   for( i = 0; i < mesh->mNumVertices; ++i ){
      tmp = mesh->mTextureCoords[0][i];
      //important!
      //This is done because most images have the top y-axis inversed with OpenGL's top y-axis.
      //or conver in shader
      uvs.push_back( glm::vec2( tmp.x, 1.0 - tmp.y ) );
   }
   //normals:
   /*
      Normalne
   */
   normals.reserve( mesh->mNumVertices );
   for( i = 0; i < mesh->mNumVertices; ++i ){
      tmp = mesh->mNormals[i];
      normals.push_back( vec3( tmp.x, tmp.y, tmp.z ) );
   }
   //indices:
   /*
      Kolejność rysowania trójkątów oraz jak każdy jest reprezentowany przez wierzchołki.
   */
   indices.reserve( 3*mesh->mNumFaces );
   for( i = 0; i < mesh->mNumFaces; ++i ){
      indices.push_back( mesh->mFaces[i].mIndices[0] );
      indices.push_back( mesh->mFaces[i].mIndices[1] );
      indices.push_back( mesh->mFaces[i].mIndices[2] );
   }
   return true;
}