Wednesday, June 23, 2021

Python shape modeling using OpenGL render mechanism, cylinders, prisms, cones and pyramids

This code is basically used to render cylinders, prisms,  cones, and pyramids using python and an OpenGL library. The script is run on pycharm. You may obtain how it has been run on the link: ==> Click here 



import glfw
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
import numpy as np
import pyrr

from math import pi, sin, cos

# First install the neccesary packages as shown above

vertex_src = """
# version 330

layout(location = 0) in vec3 a_position;
layout(location = 1) in vec3 a_color;

uniform mat4 rotation;

out vec3 v_color;

void main()
{
gl_Position = rotation * vec4(a_position, 1.0);
v_color = a_color;
}
"""

fragment_src = """
# version 330

in vec3 v_color;
out vec4 out_color;

void main()
{
out_color = vec4(v_color, 1.0);
}
"""

def window_resize(window, width, height): # the window to display the shader
glViewport(0, 0, width, height)

# initializing glfw library
if not glfw.init():
raise Exception("glfw can not be initialized!")

# creating the window
window = glfw.create_window(1280, 720, "My OpenGL window", None, None)

# check if window was created
if not window:
glfw.terminate()
raise Exception("glfw window can not be created!")

# set window's position
glfw.set_window_pos(window, 400, 200)

# set the callback function for window resize
glfw.set_window_size_callback(window, window_resize)

# make the context current
glfw.make_context_current(window)


# Size of the both which is being rendered. It has a dimension of width, height, and depth which is defined in
# the following positional vector forms as a point of the triangle.....


class plane (object):
def setVertex(self=1, uStart=-1, uEnd=1, uResolution=14, vStart=-1, vEnd=1, vResolution=14, R=0.0, G=1.0, B=0.5):
# generate set of points in the function
deltaU = ((uEnd - uStart) / uResolution)
deltaV = ((vEnd - vStart) / vResolution)

positions = []
pos = []
for uIndex in range(uResolution + 1):
vArray = []
sumArray = []
for vIndex in range(vResolution + 1):
u = uStart + uIndex * deltaU
v = vStart + vIndex * deltaV
vArray.append([u, v, 0.0, R, G, B])
sumArray = sumArray + vArray[vIndex]
positions += vArray
pos = []
for a in positions: # for flatten operation of the array
pos += a
return pos


class ellipse(object): # made a parametric ellipse equations
def setVertex(self=1, uStart=0, uEnd=2*pi, uResolution=112, vStart=0, vEnd=pi, vResolution=112,
r1=0.41, r2=0.81, r3=0.51, R=0.0, G=1.0, B=0.5):
# generate set of points in the function
deltaU = ((uEnd - uStart) / uResolution)
deltaV = ((vEnd - vStart) / vResolution)

positions = []
pos = []
for uIndex in range(uResolution + 1):
vArray = []
sumArray = []
for vIndex in range(vResolution + 1):
u = uStart + uIndex * deltaU
v = vStart + vIndex * deltaV
x = r1*cos(u)*sin(v)
y = r2*sin(u)*sin(v)
z = r3*cos(v)
vArray.append([x, y, z, R, G, B])
sumArray = sumArray + vArray[vIndex]
positions += vArray
pos = []
for a in positions: # for flatten operation of the array
pos += a
return pos


class sphere(object): # made a parametric sphere equations
def setVertex(self=1, uStart=0, uEnd=2*pi, uResolution=112, vStart=0, vEnd=pi, vResolution=112,
r=0.41, R=1.0, G=0.0, B=0.5):
# generate set of points in the function
deltaU = ((uEnd - uStart) / uResolution)
deltaV = ((vEnd - vStart) / vResolution)

positions = []
pos = []
for uIndex in range(uResolution + 1):
vArray = []
sumArray = []
for vIndex in range(vResolution + 1):
u = uStart + uIndex * deltaU
v = vStart + vIndex * deltaV
x = r*cos(u)*sin(v)
y = r*sin(u)*sin(v)
z = r*cos(v)

vArray.append([x,y, z, R, G, B])
sumArray = sumArray + vArray[vIndex]
positions += vArray
pos = []
for a in positions: # for flatten operation of the array
pos += a
return pos


class cylinder(object): # made a parametric cylinder, cone, and prisms equations
def setVertex(self=1, uStart=0, uEnd=2*pi, uResolution=112, vStart=0, vEnd=1, vResolution=112, h=1,
r1=0, r2=0.5, R=1.0, G=0.0, B=0.5):
# generate set of points in the function
deltaU = ((uEnd - uStart) / uResolution)
deltaV = ((vEnd - vStart) / vResolution)
# To draw a cone just make one of the radius as zero
positions = []
pos = []
for uIndex in range(uResolution + 1):
vArray = []
sumArray = []
for vIndex in range(vResolution + 1):
u = uStart + uIndex * deltaU
v = vStart + vIndex * deltaV
x = (v*r1+(1-v)*r2)*sin(u)
y = h*(v-1/2)
z = (v*r1+(1-v)*r2)*cos(u)

vArray.append([x, y, z, R, G, B])
sumArray = sumArray + vArray[vIndex]
positions += vArray
pos = []
for a in positions: # for flatten operation of the array
pos += a
return pos


class orderData(object):
def setOrder(uStart=-1, uEnd=1, uResolution=112, vStart=-1, vEnd=1, vResolution=112):
# group vertex data in to triangles
positionData = []

for xIndex in range(uResolution):
A = []
B = []
for yIndex in range(vResolution + 1):
A.append(
[xIndex * (vResolution + 1) + yIndex] + [xIndex * (vResolution + 1) + yIndex + (vResolution + 1)] +
[xIndex * (vResolution + 1) + yIndex + (vResolution + 2)] + [xIndex * (vResolution + 1) + yIndex] +
[xIndex * (vResolution + 1) + yIndex + (vResolution + 2)] + [
xIndex * (vResolution + 1) + yIndex + 1])
del A[vResolution]
B += A

for a in B:
positionData += a
return positionData


positionData = cylinder.setVertex()
indices = orderData.setOrder() # this shows the order of the rendering mechanism i.e the points rotation for triangle

vertices = np.array(positionData, dtype=np.float32)
indices = np.array(indices, dtype=np.uint32)

shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER))

# Vertex Buffer Object
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

# Element Buffer Object
EBO = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)

glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))

glEnableVertexAttribArray(1)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))

glUseProgram(shader)
glClearColor(0, 0.1, 0.1, 1)
glEnable(GL_DEPTH_TEST)

rotation_loc = glGetUniformLocation(shader, "rotation")

# the main application loop
while not glfw.window_should_close(window):
glfw.poll_events()

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time())
rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time())

# glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x * rot_y)
# glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x @ rot_y)
glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, pyrr.matrix44.multiply(rot_x, rot_y))

glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)

glfw.swap_buffers(window)

# terminate glfw, free up allocated resources
glfw.terminate()

Monday, June 14, 2021

Python shape modeling using OpenGL render mechanism


This code is basically used to render a box using a python and an OpenGL library. The script is run on pycharm. You may obtain how it has been run on the link: ==> Click here 



import glfw
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
import numpy as np
import pyrr

vertex_src = """
# version 330

layout(location = 0) in vec3 a_position;
layout(location = 1) in vec3 a_color;

uniform mat4 rotation;

out vec3 v_color;

void main()
{
gl_Position = rotation * vec4(a_position, 1.0);
v_color = a_color;
}
"""

fragment_src = """
# version 330

in vec3 v_color;
out vec4 out_color;

void main()
{
out_color = vec4(v_color, 1.0);
}
"""

def window_resize(window, width, height): # the window to display the shader
glViewport(0, 0, width, height)

# initializing glfw library
if not glfw.init():
raise Exception("glfw can not be initialized!")

# creating the window
window = glfw.create_window(1280, 720, "My OpenGL window", None, None)

# check if window was created
if not window:
glfw.terminate()
raise Exception("glfw window can not be created!")

# set window's position
glfw.set_window_pos(window, 400, 200)

# set the callback function for window resize
glfw.set_window_size_callback(window, window_resize)

# make the context current
glfw.make_context_current(window)


# Size of the both which is being rendered. It has a dimension of width, height,
# and depth which is defined in
# the following positional vector forms as a point of the triangle.....
width=0.5
height=0.5
depth=0.5

P0 =[-width / 2, -height / 2, -depth / 2, 1.0, 0.0, 0.0] # Vertex + color of
P1 = [width / 2, -height / 2, -depth / 2, 0.0, 0.0, 1.0]
P2 = [-width / 2, height / 2, -depth / 2, 1.0, 0.0, 0.0]
P3 = [width / 2, height / 2, -depth / 2, 1.0, 0.0, 0.0]
P4 = [-width / 2, -height / 2, depth / 2, 1.0, 0.0, 0.0]
P5 = [width / 2, -height / 2, depth / 2, 0.0, 0.0, 1.0]
P6 = [-width / 2, height / 2, depth / 2, 1.0, 0.5, 0.0]
P7 = [width / 2, height / 2, depth / 2, 1.0, 0.5, 0.0]

positionData = [P0, P1, P2, P3, P4, P5, P6, P7]


indices = [0, 1, 3, 3, 2, 0, # this shows the order of the rendering mechanism i.e the points rotation for triangle
5, 1, 3, 3, 7, 5,
4, 5, 7, 7, 6, 4,
4, 0, 2, 2, 6, 4,
6, 7, 3, 3, 2, 6,
4, 5, 1, 1, 0, 4]

vertices = np.array(positionData, dtype=np.float32)
indices = np.array(indices, dtype=np.uint32)

shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER))

# Vertex Buffer Object
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

# Element Buffer Object
EBO = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)

glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))

glEnableVertexAttribArray(1)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))

glUseProgram(shader)
glClearColor(0, 0.1, 0.1, 1)
glEnable(GL_DEPTH_TEST)

rotation_loc = glGetUniformLocation(shader, "rotation")

# the main application loop
while not glfw.window_should_close(window):
glfw.poll_events()

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time())
rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time())

# glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x * rot_y)
# glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x @ rot_y)
glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, pyrr.matrix44.multiply(rot_x, rot_y))

glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)

glfw.swap_buffers(window)

# terminate glfw, free up allocated resources
glfw.terminate()

# let we run under pycharm ......