Skip to content

天楚锐齿

人工智能 云计算 大数据 物联网 IT 通信 嵌入式

天楚锐齿

  • 下载
  • 物联网
  • 云计算
  • 大数据
  • 人工智能
  • Linux&Android
  • 网络
  • 通信
  • 嵌入式
  • 杂七杂八

使用Python渲染OpenGL的.obj和.mtl文件

2022-12-13
安装:
安装python,略。
安装pip,略。
安装其他库:
DOS> pip install pygame
DOS> pip install PyOpenGL
DOS> pip install numpy
DOS> pip install trimesh
DOS> pip install “pyglet<2”
DOS> pip install scipy
使用:
view.py:
# Basic OBJ file viewer. needs objloader from:
#  http://www.pygame.org/wiki/OBJFileLoader
# LMB + move: rotate
# RMB + move: pan
# Scroll wheel: zoom in/out
import sys, pygame
from pygame.locals import *
from pygame.constants import *
from OpenGL.GL import *
from OpenGL.GLU import *
# IMPORT OBJECT LOADER
from objloader import *
pygame.init()
viewport = (800,600)
hx = viewport[0]/2
hy = viewport[1]/2
srf = pygame.display.set_mode(viewport, OPENGL | DOUBLEBUF)
glLightfv(GL_LIGHT0, GL_POSITION,  (-40, 200, 100, 0.0))
glLightfv(GL_LIGHT0, GL_AMBIENT, (0.2, 0.2, 0.2, 1.0))
glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.5, 0.5, 0.5, 1.0))
glEnable(GL_LIGHT0)
glEnable(GL_LIGHTING)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)           # most obj files expect to be smooth-shaded
# LOAD OBJECT AFTER PYGAME INIT
obj = OBJ(sys.argv[1], swapyz=True)
clock = pygame.time.Clock()
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
width, height = viewport
gluPerspective(90.0, width/float(height), 1, 100.0)
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_MODELVIEW)
rx, ry = (0,0)
tx, ty = (0,0)
zpos = 5
rotate = move = False
while 1:
    clock.tick(30)
    for e in pygame.event.get():
        if e.type == QUIT:
            sys.exit()
        elif e.type == KEYDOWN and e.key == K_ESCAPE:
            sys.exit()
        elif e.type == MOUSEBUTTONDOWN:
            if e.button == 4: zpos = max(1, zpos-1)
            elif e.button == 5: zpos += 1
            elif e.button == 1: rotate = True
            elif e.button == 3: move = True
        elif e.type == MOUSEBUTTONUP:
            if e.button == 1: rotate = False
            elif e.button == 3: move = False
        elif e.type == MOUSEMOTION:
            i, j = e.rel
            if rotate:
                rx += i
                ry += j
            if move:
                tx += i
                ty -= j
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    # RENDER OBJECT
    glTranslate(tx/20., ty/20., – zpos)
    glRotate(ry, 1, 0, 0)
    glRotate(rx, 0, 1, 0)
    glCallList(obj.gl_list)
    pygame.display.flip()
objloader.py:
import numpy
import pygame
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def MTL(filename):
    contents = {}
    mtl = None
    for line in open(filename, “r”):
        if line.startswith(‘#’): continue
        values = line.split()
        if not values: continue
        if values[0] == ‘newmtl’:
            mtl = contents[values[1]] = {}
        elif mtl is None:
            raise (ValueError, “mtl file doesn’t start with newmtl stmt”)
        elif values[0] == ‘map_Kd’:
            # load the texture referred to by this declaration
            mtl[values[0]] = values[1]
            print(mtl[‘map_Kd’])
            surf = pygame.image.load(mtl[‘map_Kd’])
            image = pygame.image.tostring(surf, ‘RGBA’, 1)
            ix, iy = surf.get_rect().size
            texid = mtl[‘texture_Kd’] = glGenTextures(1)
            glBindTexture(GL_TEXTURE_2D, texid)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                GL_LINEAR)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                GL_LINEAR)
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA,
                GL_UNSIGNED_BYTE, image)
        else:
            mtl[values[0]] = map(float, values[1:])
    return contents
class OBJ:
    def __init__(self, filename, swapyz=False):
        “””Loads a Wavefront OBJ file. “””
        self.vertices = []
        self.normals = []
        self.texcoords = []
        self.faces = []
        material = None
        for line in open(filename, “r”):
            if line.startswith(‘#’): continue
            values = line.split()
            if not values: continue
            if values[0] == ‘v’:
                # v = map(float, values[1:4])
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.vertices.append(v)
            elif values[0] == ‘vn’:
                # v = map(float, values[1:4])
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.normals.append(v)
            elif values[0] == ‘vt’:
                # self.texcoords.append(map(float, values[1:3]))
                self.texcoords.append(list(map(float, values[1:3])))
            elif values[0] in (‘usemtl’, ‘usemat’):
                material = values[1]
            elif values[0] == ‘mtllib’:
                self.mtl = MTL(values[1])
            elif values[0] == ‘f’:
                face = []
                texcoords = []
                norms = []
                for v in values[1:]:
                    w = v.split(‘/’)
                    face.append(int(w[0]))
                    if len(w) >= 2 and len(w[1]) > 0:
                        texcoords.append(int(w[1]))
                    else:
                        texcoords.append(0)
                    if len(w) >= 3 and len(w[2]) > 0:
                        norms.append(int(w[2]))
                    else:
                        norms.append(0)
                self.faces.append((face, norms, texcoords, material))
        self.gl_list = glGenLists(1)
        glNewList(self.gl_list, GL_COMPILE)
        glEnable(GL_TEXTURE_2D)
        glFrontFace(GL_CCW)
        for face in self.faces:
            vertices, normals, texture_coords, material = face
            mtl = self.mtl[material]
            if ‘texture_Kd’ in mtl:
                # use diffuse texmap
                glBindTexture(GL_TEXTURE_2D, mtl[‘texture_Kd’])
            else:
                # just use diffuse colour
                tmpList = list(mtl[‘Kd’])
                listLen = len(tmpList)
                if listLen == 1:
                    glColor(tmpList[0])
                elif listLen == 2:
                    glColor(tmpList[0], tmpList[1])
                elif listLen == 3:
                    glColor(tmpList[0], tmpList[1], tmpList[2])
                elif listLen == 4:
                    glColor(tmpList[0], tmpList[1], tmpList[2], tmpList[3])
                #glColor(*mtl[‘Kd’])
            glBegin(GL_POLYGON)
            for i in range(len(vertices)):
                if normals[i] > 0:
                    glNormal3fv(self.normals[normals[i] – 1])
                if texture_coords[i] > 0:
                    glTexCoord2fv(self.texcoords[texture_coords[i] – 1])
                glVertex3fv(self.vertices[vertices[i] – 1])
            glEnd()
        glDisable(GL_TEXTURE_2D)
        glEndList()
运行:
需要把上面两个源文件和.obj、.mtl、.png等资源文件放到一个目录下:
DOS> python view.py  uploads_files_3746622_FK8.obj
(obj文件里面含有需要的mtl文件名,mtl文件里面含有需要的.png等其他资源文件名)

Post navigation

Previous Post:

用LVGL图形库绘制二维码

Next Post:

SpringBoot把本地的第三方jar文件打包进jar包

发表回复 取消回复

要发表评论,您必须先登录。

个人介绍

需要么,有事情这里找联系方式:关于天楚锐齿

=== 美女同欣赏,好酒共品尝 ===

微信扫描二维码赞赏该文章:

扫描二维码分享该文章:

分类

  • Linux&Android (84)
  • Uncategorized (1)
  • 下载 (28)
  • 云计算 (39)
  • 人工智能 (10)
  • 大数据 (36)
  • 嵌入式 (34)
  • 杂七杂八 (35)
  • 物联网 (65)
  • 网络 (28)
  • 通信 (22)

归档

近期文章

  • 安装JumpServer作为堡垒机
  • xshell通过SOCKS隧道和代理实现ssh登录其他内网服务器
  • 使用stub_status和vts模块进行nginx性能监控
  • 国内使用Google的Gemini AI下AntiGravity的方式
  • 抖店云的虚机用Nginx代理解码抖店订单

近期评论

  • linux爱好者 发表在《Linux策略路由及iptables mangle、ip rule、ip route关系及一种Network is unreachable错误》
  • maxshu 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • Ambition 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • Ambition 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • maxshu 发表在《Android9下用ethernet 的Tether模式来做路由器功能》

阅读量

  • 使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序 - 26,006次阅读
  • 卸载深信服Ingress、SecurityDesktop客户端 - 20,220次阅读
  • 车机技术之车规级Linux-Automotive Grade Linux(AGL) - 11,767次阅读
  • 在Android9下用ndk编译vSomeIP和CommonAPI以及使用例子 - 10,140次阅读
  • linux下的unbound DNS服务器设置详解 - 10,016次阅读
  • linux的tee命令导致ssh客户端下的shell卡住不动 - 9,298次阅读
  • Linux策略路由及iptables mangle、ip rule、ip route关系及一种Network is unreachable错误 - 9,052次阅读
  • 车机技术之360°全景影像(环视)系统 - 9,014次阅读
  • Windows下安装QEMU并在qemu上安装ubuntu和debian - 8,584次阅读
  • 车机技术之Android Automotive - 8,501次阅读

其他操作

  • 注册
  • 登录
  • 条目 feed
  • 评论 feed
  • WordPress.org

联系方式

地址
深圳市科技园

时间
周一至周五:  9:00~12:00,14:00~18:00
周六和周日:10:00~12:00

标签

android AT命令 CAN centos Hadoop hdfs ip ipv6 java kickstart linux mapreduce mini6410 modem nova OAuth openstack python socket ssh uboot 使用 内核 协议 安装 嵌入式 性能 报表 授权 数据 数据库 月报 模型 汽车 深度学习 源代码 统计 编译 网络 脚本 虚拟机 调制解调器 车机 迁移 金融
© 2026 天楚锐齿 | Powered by WordPress | Theme by MadeForWriters