Skip to content

Instantly share code, notes, and snippets.

@gottadiveintopython
Last active April 29, 2021 21:17
Show Gist options
  • Save gottadiveintopython/e597acfb24463418f7145f7a12e5f5fe to your computer and use it in GitHub Desktop.
Save gottadiveintopython/e597acfb24463418f7145f7a12e5f5fe to your computer and use it in GitHub Desktop.
My first time 3D graphics on Kivy
from kivy.base import EventLoop, runTouchApp
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.graphics import RenderContext
from kivy.properties import NumericProperty
from kivy.graphics.transformation import Matrix
from kivy.clock import Clock
EventLoop.ensure_window()
class CustomizedMesh(Factory.Mesh):
def __init__(self, *args, **kwargs):
kwargs['fmt'] = [(b'v_pos', 3, 'float'), ]
super().__init__(*args, **kwargs)
Factory.register('CustomizedMesh', cls=CustomizedMesh)
Builder.load_string(r'''
<Renderer>:
canvas:
PushMatrix:
Translate:
z: -2
Rotate:
angle: root.angle
axis: 0.5, 0.7, 0
CustomizedMesh:
vertices:
[ # 立方体
.5, .5, .5,
.5, .5, -0.5,
-0.5, .5, -0.5,
-0.5, .5, .5,
.5, -0.5, .5,
.5, -0.5, -0.5,
-0.5, -0.5, -0.5,
-0.5, -0.5, .5,
]
indices:
[
0, 1, 1, 2, 2, 3, 3, 0,
4, 5, 5, 6, 6, 7, 7, 4,
0, 4, 1, 5, 2, 6, 3, 7,
]
mode: 'lines'
PopMatrix:
''')
class Renderer(Factory.Widget):
angle = NumericProperty()
def __init__(self, **kwargs):
self.canvas = RenderContext()
self.canvas.shader.source = './simple.glsl'
super().__init__(**kwargs)
Clock.schedule_interval(self._update_angle, 0)
def _update_angle(self, dt):
self.angle += dt * 20
def on_size(self, __, size):
aspect_ratio = self.width / float(self.height)
projection_mat = Matrix().view_clip(
-aspect_ratio, aspect_ratio, -1, 1, 1, 100, 1)
self.canvas['projection_mat'] = projection_mat
root = Renderer()
runTouchApp(root)
# root = Builder.load_string(r'''
# FloatLayout:
# RelativeLayout:
# pos: 100, 100
# ''')
# renderer = Renderer()
# root.children[0].add_widget(renderer)
# runTouchApp(root)
---VERTEX SHADER---
#ifdef GL_ES
precision highp float;
#endif
attribute vec3 v_pos;
uniform mat4 modelview_mat;
uniform mat4 projection_mat;
void main (void) {
gl_Position = projection_mat * modelview_mat * vec4(v_pos, 1.0);
}
---FRAGMENT SHADER---
#ifdef GL_ES
precision highp float;
#endif
void main(void)
{
gl_FragColor = vec4(1.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment