| 模式 | 特點 | 適用場景 |
| 立即模式 (Immediate Mode) | 開發者手動渲染每幀,控制精細,速度較快 | 高效能遊戲、自訂渲染管線 |
| 保留模式 (Retained Mode) | 建立場景圖,設定關鍵幀,動畫由引擎自動插值,程式碼簡單 | 場景展示、簡單動畫、快速開發 |
M3G 允許混合使用兩種模式。
核心類別架構
Graphics3D:Singleton,3D 渲染目標綁定與繪製入口
World:場景根節點,包含 Camera、Light、Background、3D 物體樹
Camera:觀察者視角、投影矩陣 (透視/正交)
Mesh、TriangleStripArray、IndexBuffer:幾何體資料 (頂點、法線、紋理座標)
Appearance、Material、Texture2D:外觀屬性
Loader:從 .m3g 檔案載入完整場景 (可用 3ds Max 等工具匯出)
最小可執行範例:旋轉金字塔
來源:Sony Ericsson 官方範例,可在 WTK 2.2 模擬器執行。
1. 取得 Graphics3D 實例
Graphics3D g3d = Graphics3D.getInstance();
2. Canvas 中渲染迴路
public class MyCanvas extends Canvas implements Runnable {
private Graphics3D g3d = Graphics3D.getInstance();
private World world;
public void run() {
Graphics g = getGraphics();
while (true) {
try {
g3d.bindTarget(g);
// 更新場景 (動畫)
world.animate(System.currentTimeMillis() - startTime);
// 渲染
g3d.render(world);
} finally {
g3d.releaseTarget();
}
flushGraphics();
Thread.sleep(30); // 約 33 FPS
}
}
protected void paint(Graphics g) {
// 若不使用獨立執行緒,可在這裡渲染
}
}
3. 建立場景與攝影機
world = new World();
Camera cam = new Camera();
world.addChild(cam);
float w = getWidth();
float h = getHeight();
cam.setPerspective(60.0f, w/h, 0.1f, 50.0f); // fov, aspect, near, far
world.setActiveCamera(cam);
4. 程式化建立金字塔 Mesh
private Mesh createPyramid() {
// 頂點座標 (x,y,z)
short[] verts = {
0, 10, 0, // 頂點
-10, -10, 10, // 底面四角
10, -10, 10,
10, -10,-10,
-10, -10,-10
};
// 三角形索引 (4 側面 + 2 底面三角形)
byte[] indices = {
0,1,2, 0,2,3, 0,3,4, 0,4,1, // 四側面
1,3,2, 1,4,3 // 底面
};
VertexArray positions = new VertexArray(5, 3, 2); // 5點, 3維, short
positions.set(0, 5, verts);
TriangleStripArray strips = new TriangleStripArray(6, new int[]{3,3,3,3,3,3});
strips.setIndices(0, indices, 18);
Mesh mesh = new Mesh(positions, strips, null); // Appearance 稍後設定
mesh.setTranslation(0, 0, -30); // 移入螢幕內
return mesh;
}
5. 加入場景並啟動動畫
Mesh pyramid = createPyramid();
world.addChild(pyramid);
// 在執行緒中旋轉
public void run() {
// ...
pyramid.postRotate(3.0f, 0, 1, 0); // 繞 Y 軸旋轉 3 度
// ...
}
從 .m3g 檔案載入場景 (生產建議)
try {
Object[] objs = Loader.load("/scene.m3g"); // 從 JAR 內資源載入
world = (World) objs[0]; // 第一個物件通常是 World
// 取得場景中定義的 Camera
Camera cam = world.getActiveCamera();
} catch (Exception e) {
e.printStackTrace();
}
- 使用 3ds Max + M3G 匯出外掛建模,大幅降低程式碼複雜度
- 支援動畫軌跡、骨骼動畫、材質、貼圖完整保留
WTK 2.2 內建支援與測試
- WTK 2.2 已內建 M3G 實作,無需額外安裝
- 專案設定:
API Selection → Mobile 3D Graphics (JSR 184)
- 參考範例:
WTK2.2/apps/Demo3D
效能優化建議
- 減少
postRotate 等矩陣運算頻率,改用關鍵幀插值
- 合併 Mesh 減少 Draw Call
- 使用
TriangleStripArray 而非獨立三角形
- 貼圖尺寸採 2 的冪次方,啟用 Mipmap
- 針對低端裝置提供 LOD (Level of Detail) 版本
M3G 為 J2ME 帶來了前所未有的 3D 表現力,雖然智慧型手機時代已由 OpenGL ES 取代,但在功能機、嵌入式裝置維護專案中仍具參考價值。
- 上一篇文章: J2ME Polish + Eclipse (Mepose) 整合環境建置完整實戰筆記
- 下一篇文章: J2ME 3D 程式設計實戰:第一個 M3G 程式完整原始碼解析
Copyright ©
程式碼之家 All Rights Reserved