1 说明:
=====
1.1 画3d正方体=cube,用python编程,需要几行代码呢?今天就来看看简洁的python和其强大的库文件。
1.2 相关包安装,建议采用pip法,用国内源安装较好。
pip install -i https://mirrors.aliyun.com/pypi/simple 软件名
#本机采用
sudo pip3.8 install -i https://mirrors.aliyun.com/pypi/simple 软件名
1.3 环境:
华为笔记本电脑、深度deepin-linux操作系统、python3.8和微软vscode编辑器。
2 示例:
===排行榜===
2.1 第9名:
===========
panda3d法,65行代码,迪士尼公司开源项目。
2.1.1 9-panda3d法-65.py代码:
from direct.showbase.Showbase import ShowBase
from direct.showbase.DirectObject import DirectObject
from panda3d.core import GeomVertexFormat, GeomVertexData
from panda3d.core import Geom, GeomTriangles, GeomVertexWriter
from panda3d.core import GeomNode,PerspectiveLens,LVector3
base = ShowBase()
base.disableMouse()
base.camera.setPos(0, -10, 0)
def normalized(*args):
myVec = LVector3(*args)
myVec.normalize()
return myVec
def makeSquare(x1, y1, z1, x2, y2, z2):
format = GeomVertexFormat.getV3n3cpt2()
vdata = GeomVertexData('square', format, Geom.UHDynamic)
vertex = GeomVertexWriter(vdata, 'vertex')
normal = GeomVertexWriter(vdata, 'normal')
color = GeomVertexWriter(vdata, 'color')
texcoord = GeomVertexWriter(vdata, 'texcoord')
if x1 != x2:
vertex.addData3(x1, y1, z1)
vertex.addData3(x2, y1, z1)
vertex.addData3(x2, y2, z2)
vertex.addData3(x1, y2, z2)
normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1))
normal.addData3(normalized(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1))
normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1))
normal.addData3(normalized(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1))
else:
vertex.addData3(x1, y1, z1)
vertex.addData3(x2, y2, z1)
vertex.addData3(x2, y2, z2)
vertex.addData3(x1, y1, z2)
normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1))
normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1))
normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1))
normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1))
color.addData4f(1.0, 0.0, 0.0, 1.0)
texcoord.addData2f(0.0, 1.0)
texcoord.addData2f(0.0, 0.0)
texcoord.addData2f(1.0, 0.0)
texcoord.addData2f(1.0, 1.0)
tris = GeomTriangles(Geom.UHDynamic)
tris.addVertices(0, 1, 3)
tris.addVertices(1, 2, 3)
square = Geom(vdata)
square.addPrimitive(tris)
return square
square0 = makeSquare(-1, -1, -1, 1, -1, 1)
square1 = makeSquare(-1, 1, -1, 1, 1, 1)
square2 = makeSquare(-1, 1, 1, 1, -1, 1)
square3 = makeSquare(-1, 1, -1, 1, -1, -1)
square4 = makeSquare(-1, -1, -1, -1, 1, 1)
square5 = makeSquare(1, -1, -1, 1, 1, 1)
snode = GeomNode('square')
snode.addGeom(square0)
snode.addGeom(square1)
snode.addGeom(square2)
snode.addGeom(square3)
snode.addGeom(square4)
snode.addGeom(square5)
cube = render.attachNewNode(snode)
cube.hprInterval(1.5, (360, 360, 360)).loop()
cube.setTwoSided(True)
base.run()
2.1.2 效果图:
2.2 第8名:
==========
pygame法,42行代码,配合OpenGL
2.2.1 8-pygame法-42.py代码:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
pygame.init()
pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF)
#---元组定义---
#定义正方体的xyz坐标点
CUBE_POINTS = ((0.5, -0.5, -0.5), (0.5, 0.5, -0.5),(-0.5, 0.5, -0.5), (-0.5, -0.5, -0.5),(0.5, -0.5, 0.5), (0.5, 0.5, 0.5),(-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5))
#定义RGB颜色
CUBE_COLORS = ((1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 0),(1, 0, 1), (1, 1, 1), (0, 0, 1), (0, 1, 1))
# 定义面,四个点构成一个面
CUBE_QUAD_VERTS = ((0, 1, 2, 3), (3, 2, 7, 6), (6, 7, 5, 4),(4, 5, 1, 0), (1, 5, 7, 2), (4, 0, 3, 6))
# 定义线,两个点构成一个线
CUBE_EDGES = ((0,1), (0,3), (0,4), (2,1), (2,3), (2,7),(6,3), (6,4), (6,7), (5,1), (5,4), (5,7),)
def drawcube():
allpoints = list(zip(CUBE_POINTS, CUBE_COLORS))
glBegin(GL_QUADS)
for face in CUBE_QUAD_VERTS:
for vert in face:
pos, color = allpoints[vert]
glColor3fv(color)
glVertex3fv(pos)
glEnd()
glColor3f(0, 0, 0)
glBegin(GL_LINES)
for line in CUBE_EDGES:
for vert in line:
pos, color = allpoints[vert]
glVertex3fv(pos)
glEnd()
def main():
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
gluPerspective(45.0,640/480.0,0.1,100.0)
glTranslatef(0.0, 0.0, -3.0)
glRotatef(25, 1, 0, 0)
while True:
event = pygame.event.poll()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
break
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glRotatef(1,0,1,0)
drawcube()
pygame.display.flip()
if __name__ == '__main__':
main()
2.2.2 效果图:
2.3 第7名:
===========
vispy法,30行代码。
2.3.1 7-vispy法-30.py代码:
from vispy import app, gloo, visuals
from vispy.visuals.transforms import MatrixTransform
class Canvas(app.Canvas):
def __init__(self):
#窗口大小
app.Canvas.__init__(self, keys='interactive', size=(1300, 1200))
self.box = visuals.BoxVisual(width=1, height=1, depth=1,edge_color='b')
self.theta = self.phi =0
self.transform = MatrixTransform()
self.box.transform = self.transform
self.show()
self.timer = app.Timer(connect=self.rotate)
self.timer.start(0.016)
def rotate(self, event):
self.theta = .5
self.phi = .5
self.transform.reset()
self.transform.rotate(self.theta, (0, 0, 1))
self.transform.rotate(self.phi, (0, 1, 0))
self.transform.scale((100, 100, 0.001))
self.transform.translate((200, 200))
self.update()
def on_resize(self, event):
vp = (0, 0, self.physical_size[0], self.physical_size[1])
self.context.set_viewport(*vp)
self.box.transforms.configure(canvas=self, viewport=vp)
def on_draw(self, ev):
#背景颜色设置
gloo.clear(color='black', depth=True)
self.box.draw()
win = Canvas()
app.run()
2.3.2 效果图:
2.4 第6名:
==========
vtk法,19行代码。
2.4.1 6-vtk法-19.py代码:
import vtk
#实例化cube
cube=vtk.vtkCubeSource()
#定义三边长10,长宽高
cube.SetXLength(10)
cube.SetZLength(10)
cube.SetYLength(10)
cubeMapper = vtk.vtkPolyDataMapper()
cubeMapper.SetInputConnection(cube.GetOutputPort())
cubeActor = vtk.vtkActor()
cubeActor.SetMapper(cubeMapper)
#cube表面为白色1.0,1.0,1.0
cubeActor.GetProperty().SetColor(0.1,0.7,0.1) #cube表面为草绿色
#渲染器设置:实例化
ren=vtk.vtkRenderer()
ren.AddActor(cubeActor) #将正方体加入渲染器中
ren.SetBackground(0.1,0.2,0.4) #窗口背景颜色:蓝色
#定期渲染器窗口
renWin=vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
# 创建窗口交互器
iren=vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
iren.Start()
2.4.2 效果图:
2.5 第5名
==========
matplotlib法,16行代码
2.5.1 5-matplotlib法-16.py代码:
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def plot_linear_cube(x, y, z, dx, dy, dz, color='red'):
fig = plt.figure()
ax = Axes3D(fig)
xx = [x, x, x dx, x dx, x]
yy = [y, y dy, y dy, y, y]
kwargs = {'alpha': 1, 'color': color}
ax.plot3D(xx, yy, [z]*5, **kwargs)
ax.plot3D(xx, yy, [z dz]*5, **kwargs)
ax.plot3D([x, x], [y, y], [z, z dz], **kwargs)
ax.plot3D([x, x], [y dy, y dy], [z, z dz], **kwargs)
ax.plot3D([x dx, x dx], [y dy, y dy], [z, z dz], **kwargs)
ax.plot3D([x dx, x dx], [y, y], [z, z dz], **kwargs)
plt.show()
plot_linear_cube(0, 0, 0, 100, 100, 100)
2.5.2 效果图:
2.6 第4名:
========
visvis法,14行代码
2.6.1 4-visvis法-14.py代码:
import visvis as vv
class CustomWobject(vv.Wobject):
def __init__(self, parent):
vv.Wobject.__init__(self, parent)
def _GetLimits(self):
x1, x2 = 0, 1
y1, y2 = 0, 1
z1, z2 = 0, 1
return vv.Wobject._GetLimits(self, x1, x2, y1, y2, z1, z2)
a = vv.cla()
c = CustomWobject(a)
a.SetLimits() #x/y/z相等
app = vv.use()
app.Run()
2.6.2 效果图:
===10行代码以内的===
3 第3名:
======
pyqtgraph法,8行代码。
3.1 3-pyqtgraph法-8.py代码:
from pyqtgraph.Qt import QtGui
import pyqtgraph.opengl as gl
app = QtGui.QApplication([])
w = gl.GLViewWidget()
w.show()
b = gl.GLBoxItem() #默认大小
w.addItem(b)
app.instance().exec_()
3.2 效果图:
4 第2名:
======
pyvista法,5行代码。
4.1 2-pyvista法-5.py代码:
import pyvista as pv
#实例化box=cube=正方体
box = pv.Box()
#实例化一个画布
p = pv.Plotter()
#将box添加在画布p上进行渲染
p.add_mesh(box, color="tan", show_edges=True)
#显示
p.show()
4.2 效果图:
5 第1名:
======
冠军,vpython法,2行代码搞定。
5.1 1-vpython法-2.py代码:
from vpython import *
box()
5.2 操作和效果图:
怎么样?
python厉害不?
看似无聊,但是都是在国外大神原创性无聊的基础上无聊的。
记住,python就是一个无聊的大神无聊时发明的,加油,中国人。
科技创新,让科技创新的思维进入我们无聊时的大脑。
===自己整理并分享出来===
喜欢的人,请点赞、关注、评论、转发和收藏。
,