O3D 是一个开源的Web API,其可以创建相当牛X的基于浏览器的可交互式的3D应用。这个API在很有可能会形成以后的Web上的3D图形的标准。下面是这个API的主站点: http://code.google.com/apis/o3d/ 。O3D目前支持Windows, Mac和Linux三种平台。
下面是一些简单地使用O3D的API的如何创建一个立方体,更详细的内容请访问O3D的网站。
1)首选我们先创建一个比较原始的立方体。使用createCube()方法。
01 | function createCube(material) { |
02 | var cubeShape = g_pack.createObject( 'Shape' ); |
03 | var cubePrimitive = g_pack.createObject( 'Primitive' ); |
04 | var streamBank = g_pack.createObject( 'StreamBank' ); |
05 |
06 | cubePrimitive.material = material; |
07 | cubePrimitive.owner(cubeShape); |
08 | cubePrimitive.streamBank = streamBank; |
09 | . |
10 | . |
11 | . |
2)然后,我们需要指定一些顶点信息。
其中,我们利用三角形来构造3D图形。一个立方体有12个三角面,两个构成一个面,然后有8个顶点。
1 | cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST; |
2 | cubePrimitive.numberPrimitives = 12; // 12 triangles |
3 | cubePrimitive.numberVertices = 8; // 8 vertices in total |
4 | cubePrimitive.createDrawElement(g_pack, null ); // Create the draw element for this primitive. |
3)指定一下8个顶点的坐标。
01 | var positionArray = [ |
02 | -0.5, -0.5, 0.5, // vertex 0 |
03 | 0.5, -0.5, 0.5, // vertex 1 |
04 | -0.5, 0.5, 0.5, // vertex 2 |
05 | 0.5, 0.5, 0.5, // vertex 3 |
06 | -0.5, 0.5, -0.5, // vertex 4 |
07 | 0.5, 0.5, -0.5, // vertex 5 |
08 | -0.5, -0.5, -0.5, // vertex 6 |
09 | 0.5, -0.5, -0.5 // vertex 7 |
10 | ]; |
4)把顶点坐标数组加入Buffer中。
1 | // Create buffers containing the vertex data. |
2 | var positionsBuffer = g_pack.createObject( 'VertexBuffer' ); |
3 | var positionsField = positionsBuffer.createField( 'FloatField' , 3); |
4 | positionsBuffer.set(positionArray); |
5)把Buffer放到Stream Bank中。
1 | // Associate the positions Buffer with the StreamBank. |
2 | streamBank.setVertexStream( |
3 | g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions |
4 | 0, // semantic index: First (and only) position stream |
5 | positionsField, // field: the field this stream uses. |
6 | 0); // start_index: How many elements to skip in the field. |
6)连接点成为三角面,并把三角面两两一组组成立方面。
01 | var indicesArray = [ |
02 | 0, 1, 2, // face 1 |
03 | 2, 1, 3, |
04 | 2, 3, 4, // face 2 |
05 | 4, 3, 5, |
06 | 4, 5, 6, // face 3 |
07 | 6, 5, 7, |
08 | 6, 7, 0, // face 4 |
09 | 0, 7, 1, |
10 | 1, 7, 3, // face 5 |
11 | 3, 7, 5, |
12 | 6, 0, 4, // face 6 |
13 | 4, 0, 2 |
14 | ]; |
完整的源码请参看这里:(打开网页后查看源码)
http://o3d.googlecode.com/svn/trunk/samples/hellocube.html
最后,让我们看一看下面YouTube上的视频,你就知道这个东西有多强了。YouTube链接。