- Panda3d 1.7 Game Developer's Cookbook
- Christoph Lang
- 1279字
- 2021-04-09 21:21:48
Generating geometry at runtime
In some cases, Panda3D's model loading capabilities might not be enough for your needs. Maybe you want to procedurally generate new geometry at runtime or maybe you decided to drop the native file model file format of Panda3D in favor of your own custom data file layout. For all these cases where you need to glue together vertices by hand in order to form a model, the engine provides an API that you will learn about in this recipe.
Getting ready
As a prerequisite to the following steps, please create a new project as described in the recipe Setting up the game structure. This recipe can be found in the Chapter 1.
You will also need a texture image. Preferably it should be rectangular and in the best case be in a 2n format (64x64, 128x128, 256x256, and so on.). This recipe will use a crate texture in PNG format.
Lastly, add a directory called textures
to your project and be sure it is in Panda3D's search path. This works analogous to what you did for the models
and sounds
directories.
How to do it...
Follow these steps to learn how to create geometry on the fly:
- Copy your texture image to the
textures
directory. Name itcrate.png
. - Open
Application.py
. Insert the following code:from direct.showbase.ShowBase import ShowBase from panda3d.core import * vertices = [Vec3(1, 0, 1), Vec3(-1, 0, 1), Vec3(-1, 0, -1), Vec3(1, 0, -1)] texcoords = [Vec2(1, 1), Vec2(0, 1), Vec2(0, 0), Vec2(1, 0)] class Application(ShowBase): def __init__(self): ShowBase.__init__(self) format = GeomVertexFormat.getV3t2() geomData = GeomVertexData("box", format, Geom.UHStatic) vertexWriter = GeomVertexWriter(geomData, "vertex") uvWriter = GeomVertexWriter(geomData, "texcoord") for pos, tex in zip(vertices, texcoords): vertexWriter.addData3f(pos) uvWriter.addData2f(tex) triangles = GeomTriangles(Geom.UHStatic) triangles.addVertices(0, 1, 2) triangles.closePrimitive() triangles.addVertices(2, 3, 0) triangles.closePrimitive() geom = Geom(geomData) geom.addPrimitive(triangles) node = GeomNode("box") node.addGeom(geom) box = render.attachNewNode(node) texture = loader.loadTexture("crate.png") box.setTexture(texture) self.cam.setPos(0, -5, 0)
- Start the program. A quad with your texture on it should be rendered to the Panda3D window:
How it works...
Let's take a look at what this code is doing! We begin by creating a format descriptor for one of Panda3D's built in vertex data layouts. There are several of these layouts, which also can be completely customized, which describe what kind of data will be stored for each point in space that forms the mesh. In this particular case, we are using the getV3t2()
method to get a descriptor for a vertex layout that stores the vertex position in space using three floating point values and the texture coordinate using two float values.
We then move on to create a GeomVertexData
object, which uses the format we just requested. We also pass the Geom.UHStatic
flag, which signals the underlying rendering systems that the vertex data will not change, which allows them to enable some optimizations. Additionally, we create two GeomVertexWriter
objects—one for writing to the "vertex
" channel, which stores the positions of the points that form the mesh, and the other one for writing to the "texcoord
" channel of the point data we are adding to geomData
in the loop that follows.
What we have so far is a cloud of seemingly random points—at least to the engine. To correct this issue, we need to connect the points to form primitives, which in this case are triangles. We create a new instance of GeomTriangles
, using the Geom.UHStatic
flag again to hint that the primitives will not be changed after they are defined. Then we create two triangles by passing indices to the proper points in the vertices
list. After each triangle, we need to call the closePrimitive()
method to mark the primitive as complete and start a new one.
At this point we have a collection of points in space, stored in a GeomVertexData
object and a GeomTriangles
primitive that holds the information necessary to connect the dots and form a mesh. To get the model to the screen, we need to create a new Geom
, and add the point data and the triangle primitives. Because a model can in fact consist of multiple Geom
objects, which also can't be added directly to the scene graph, we add it to a GeomNode
. Finally, we attach the GeomNode
to the scene graph, load and apply the texture and set the camera a bit back to be able to see our creation.
There's more...
There's a lot more to say about Panda3D's procedural geometry feature than what you just saw, so take your time and keep on reading to discover what else you can do to generate geometry at runtime.
Built in vertex formats
You already saw the built in GeomVertexFormat.getV3t2()
format, but there are several more ready to use formats available:
getV3()
: Vertices store position onlygetV3c4()
: Vertex position and a RGBA color valuegetV3c4t2()
: Position, color, and texture coordinatesgetV3n3()
: Position and normal vectorgetV3n3c4()
: Position, normal, and RGBA colorgetV3n3c4t2()
: This is the most extensive format. Contains position, normal, color, and texture coordinatesgetV3n3t2()
: Position, normal vector, and texture coordinates.
There's also a packed color format, which you can use by replacing c4
in the previous methods with cp
. In this format, colors are stored into one 32-bit integer value. The best way to define color values for this format is in hexadecimal, because it lets you easily recognize the RGBA components of the color. For example, the value 0xFF0000FF is full red.
Custom vertex formats
Apart from the built-in vertex formats, Panda3D allows you to be much more flexible by defining your own custom formats. The key parts to this are the GeomVertexArrayFormat
and GeomVertexFormat
classes, which are used in the following way:
arrayFmt = GeomVertexArrayFormat() arrayFmt.addColumn(InternalName.make("normal"), 3, Geom.NTFloat32, Geom.CVector) fmt = GeomVertexFormat() fmt.addArray(arrayFmt) fmt = GeomVertexFormat.registerFormat(fmt)
In the beginning, you need to describe your vertex array data layout by adding columns. The first parameter is the channel that Panda3D is going to use the data for. Very commonly used channels are "vertex
", "color
", "normal
", "texcoord
", "tangent
", and "binormal
".
The second and third parameters are the number of components and data type the channel is using. In this sample, the normal data is composed out of three 32-bit floating point values. Legal values for the third parameter include NTFloat32
, NTUint*
, where *
is one of 8, 16, or 32, describing an unsigned integer of the according bit width as well as NTPackedDcba
and NTPackedDabc
, used for packed index and color data.
The third parameter influences how the data is going to be treated internally—for example, if and how it will be transformed if a matrix is applied to the data in the column. Possible values include:
CPoint
: Point data in 3D space, most often used for the "vertex
" channel.CVector
: A vector giving a direction in space. Use this for normals, tangents, and binormals.CTexcoord
: The data in the column contains the coordinates of texture sample points.CColor
: The data is to be treated as color values.CIndex
: The column contains table indices.COther
: Arbitrary data values.
Points and texture coordinates are transformed as points, resulting in new positions if they are involved in a matrix multiplication. Vectors of course are following different rules when being transformed, because they describe directions, not positions! It would go too far to go into the details here, but lots of material on vector math and linear algebra are freely available on Wikipedia and other websites.
Primitive types
Panda3D supports all the standard primitive types commonly known in computer graphics: Triangles, triangle strips, triangle fans, lines, line strips, and points. The according classes used to describe these primitives are GeomTriangles
, GeomTristrips
, GeomTrifans
, GeomLines
, GeomLinestrips
, and GeomPoints
.
See also
Loading models and actors, Modifying the scene graph.
- Vue.js前端開發(fā)技術(shù)
- 從零開始:Photoshop CC中文版基礎(chǔ)培訓(xùn)教程
- 對(duì)比Excel,輕松學(xué)習(xí)SQL數(shù)據(jù)分析
- AutoCAD快速自學(xué)寶典(2018中文版)
- 中文版Maya 2012實(shí)用教程(第2版)
- UI 設(shè)計(jì)入門一本就夠
- 移動(dòng)App測(cè)試的22條軍規(guī)
- Drupal Multimedia
- Talend Open Studio Cookbook
- ADOBE FLASH PROFESSIONAL CS6 標(biāo)準(zhǔn)培訓(xùn)教材
- 從零開始:Photoshop工具詳解與實(shí)戰(zhàn)
- 用Cubase輕松制作你的短視頻音樂
- 中文版Photoshop CS6全能修煉圣經(jīng)(移動(dòng)學(xué)習(xí)版)
- 魔法詞典:AI繪畫關(guān)鍵詞圖鑒(Midjourney版)
- Configuring IPCop Firewalls: Closing Borders with Open Source