哇塞,一转眼已经到了传说中的粒子系统了,学会了粒子系统就可以做出一些更好玩的效果啦!加油啦!
粒子系统,正如其名称,由各种小的粒子构成。通常用来模拟火焰,爆炸,烟,水流,火花,落叶,雨,雪等等难以用具体的形状来描述的物体。单个的粒子非常简单,可以用多边形来表示,甚至用像素表示。但是,不要小看了这样微小的粒子,当粒子的数量级达到上千,上万,甚至十万时,表现力是及其震撼的!
下面附上两张DX自带的粒子系统的截图:
帅呆了...然而我并做不出来...
粒子系统有三个特性:
1.群体性:粒子如此微小,要想成大气候,就必须聚集起来。
2.统一性:每个粒子性质相同。
3.随机性:粒子系统中的元素会随机表现出不同的特性。
简单的概括就是,整体有一致的表现,但是单独的粒子可以有不同的表现。
粒子系统的基本原理,即粒子系统的生命周期:
1.产生新的粒子
2.更新现有粒子的属性
3.删除已经消亡的粒子
4.绘制粒子
通常一次性分配足够的空间,通过数据结构管理存在的粒子以及消亡的粒子,如果粒子消亡了,不显示即可。
/*! * \file Particle.h * * \author puppet_master * \date 八月 2015 * * 粒子系统的实现 */ #ifndef __CPARTICLE_H_ #define __CPARTICLE_H_ #include "stdafx.h" #pragma once //粒子定点格式 struct POINTVERTEX { float x, y, z; float u, v; }; #define D3DFVF_POINTVERTEX (D3DFVF_XYZ | D3DFVF_TEX1) //粒子结构体定义 struct ParticleStruct { float x, y, z; //坐标 float rotationX; //绕X轴旋转角度 float rotationY; //绕Y轴旋转角度 float speed; //下落速度 float rotationSpeed; //旋转速度 }; const int PARTICLE_NUMBER = 3000; //粒子数量 const int AREA_WIDTH = 10000; //粒子系统区域宽度 const int AREA_LENGTH = 10000; //粒子系统区域长度 const int AREA_HEIGHT = 10000; //粒子系统区域高度 class CParticle { private: LPDIRECT3DDEVICE9 m_pDevice; //设备指针 ParticleStruct m_Particle[PARTICLE_NUMBER]; //粒子结构体数组 LPDIRECT3DVERTEXBUFFER9 m_pVertexBuffer; //顶点缓冲区 LPDIRECT3DTEXTURE9 m_pTexture; //粒子纹理 public: CParticle(LPDIRECT3DDEVICE9); virtual ~CParticle(void); //初始化粒子系统 bool InitParticle(); //更新粒子 bool UpdateParticle(float); //绘制粒子 bool RenderParticle(); }; #endif
.cpp文件
#include "stdafx.h" #include "Particle.h" #include <time.h> CParticle::CParticle(LPDIRECT3DDEVICE9 pDevice) { m_pDevice = pDevice; m_pVertexBuffer = NULL; m_pTexture = NULL; } CParticle::~CParticle(void) { SAFE_RELEASE(m_pVertexBuffer); SAFE_RELEASE(m_pTexture); } bool CParticle::InitParticle() { srand((unsigned int)time(0)); //初始化雪花粒子数组 for(int i = 0; i < PARTICLE_NUMBER; i++) { m_Particle[i].x = rand() % AREA_LENGTH - AREA_LENGTH / 2; m_Particle[i].y = rand() % AREA_HEIGHT; m_Particle[i].z = rand() % AREA_WIDTH - AREA_WIDTH / 2; m_Particle[i].speed = 500 + rand() % 500; m_Particle[i].rotationSpeed = 5.0f + rand() % 10 / 10.0f; } //创建雪花粒子顶点缓存 m_pDevice->CreateVertexBuffer(4 * sizeof(POINTVERTEX), 0, D3DFVF_POINTVERTEX, D3DPOOL_MANAGED, &m_pVertexBuffer, NULL); //填充顶点缓存 POINTVERTEX vertices[] = { {-10.0f, 0.0f, 0.0f, 0.0f, 1.0f}, {-10.0f, 20.0f, 0.0f, 0.0f, 0.0f}, { 10.0f, 0.0f, 0.0f, 1.0f, 1.0f}, { 10.0f, 20.0f, 0.0f, 1.0f, 0.0f} }; //加锁 VOID* pVertices; m_pVertexBuffer->Lock(0, sizeof(vertices), (void**)&pVertices, 0); //拷贝顶点数据 memcpy(pVertices, vertices, sizeof(vertices)); //解锁 m_pVertexBuffer->Unlock(); //加载纹理 D3DXCreateTextureFromFile(m_pDevice, "snow.jpg", &m_pTexture); return true; } bool CParticle::UpdateParticle(float fElapsedTime) { for(int i = 0; i < PARTICLE_NUMBER; i++) { m_Particle[i].y -= m_Particle[i].speed * fElapsedTime; if (m_Particle[i].y < 0) m_Particle[i].y = AREA_HEIGHT; m_Particle[i].rotationX += m_Particle[i].rotationSpeed * fElapsedTime; m_Particle[i].rotationY += m_Particle[i].rotationSpeed * fElapsedTime; } return true; } bool CParticle::RenderParticle() { //禁用照明 m_pDevice->SetRenderState(D3DRS_LIGHTING, false); //设置纹理 m_pDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); m_pDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); m_pDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); m_pDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); //设置Alpha混合系数 m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);//打开alpha混合 m_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);//源混合系数为1 m_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);//目标混合系数为1 //设置不剔除背面 m_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); //渲染 for (int i = 0; i < PARTICLE_NUMBER; i++) { //设置世界矩阵(这里设置为局部静态变量,类似全局变量,但是又比全局变量容易维护,作用域仅为该函数) static D3DXMATRIX matTrans, matYaw, matPitch, matWorld; D3DXMatrixRotationX(&matPitch, m_Particle[i].rotationX); D3DXMatrixRotationY(&matYaw, m_Particle[i].rotationY); D3DXMatrixTranslation(&matTrans, m_Particle[i].x, m_Particle[i].y, m_Particle[i].z); matWorld = matPitch * matYaw * matTrans; m_pDevice->SetTransform(D3DTS_WORLD, &matWorld); //设置纹理 m_pDevice->SetTexture(0, m_pTexture); //绘制相关 m_pDevice->SetStreamSource(0, m_pVertexBuffer, 0, sizeof(POINTVERTEX)); m_pDevice->SetFVF(D3DFVF_POINTVERTEX); m_pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); } //绘制完成后恢复原状态:Alpha混合,背面剔除,光照,防止出现渲染状态泄露,影响其他对象绘制 m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); m_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); m_pDevice->SetRenderState(D3DRS_LIGHTING, true); return true; }
run一下:
换个角度:
加大粒子量:
附上main函数代码:
// D3DDemo.cpp : 定义应用程序的入口点。 // #include "stdafx.h" #include "D3DDemo.h" #include "DirectInput.h" #include "Camera.h" #include "Terrain.h" #include "Mesh.h" #include "SkyBox.h" #include "Particle.h" #define MAX_LOADSTRING 100 // 全局变量: HINSTANCE hInst; // 当前实例 TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 // 此代码模块中包含的函数的前向声明: HWND g_hWnd; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); //---------改造3D窗口需要的内容------------ LPDIRECT3D9 g_pD3D = NULL; //D3D接口指针 LPDIRECT3DDEVICE9 g_pDevice = NULL; //D3D设备指针 CDirectInput* g_pDirectInput = NULL; //控制指针 CCamera* g_pCamera = NULL; //摄像机指针 CTerrain* g_pTerrian = NULL; //地形类指针 CSkyBox* g_pSkyBox = NULL; //天空盒类指针 CParticle* g_pParticle = NULL; //粒子系统指针 CMesh* g_pMesh1 = NULL; //网格对象指针1 CMesh* g_pMesh2 = NULL; //网格对象指针2 CMesh* g_pMesh3 = NULL; //网格对象指针3 D3DXMATRIX g_matWorld; //世界矩阵 void onCreatD3D() { g_pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!g_pD3D) return; //检测硬件设备能力的方法 /*D3DCAPS9 caps; ZeroMemory(&caps, sizeof(caps)); g_pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps);*/ //获得相关信息,屏幕大小,像素点属性 D3DDISPLAYMODE d3ddm; ZeroMemory(&d3ddm, sizeof(d3ddm)); g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm); //设置全屏模式 D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(d3dpp)); /*d3dpp.Windowed = false; d3dpp.BackBufferWidth = d3ddm.Width; d3dpp.BackBufferHeight = d3ddm.Height;*/ d3dpp.Windowed = true; d3dpp.BackBufferFormat = d3ddm.Format; d3dpp.BackBufferCount = 1; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;//交换后原缓冲区数据丢弃 //是否开启自动深度模板缓冲 d3dpp.EnableAutoDepthStencil = true; //当前自动深度模板缓冲的格式 d3dpp.AutoDepthStencilFormat = D3DFMT_D16;//每个像素点有16位的存储空间,存储离摄像机的距离 g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pDevice); if (!g_pDevice) return; //设置渲染状态,设置启用深度值 g_pDevice->SetRenderState(D3DRS_ZENABLE, true); //设置渲染状态,关闭灯光 //g_pDevice->SetRenderState(D3DRS_LIGHTING, false); //设置渲染状态,裁剪模式 g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); //g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) ; } void CreateMesh() { g_pMesh1 = new CMesh(g_pDevice); g_pMesh1->CreateMesh("Demon.X"); g_pMesh2 = new CMesh(g_pDevice); g_pMesh2->CreateMesh("dragon.X"); g_pMesh3 = new CMesh(g_pDevice); g_pMesh3->CreateMesh("miki.X"); } void CreateCamera() { g_pCamera = new CCamera(g_pDevice); g_pCamera->SetCameraPosition(&D3DXVECTOR3(0.0f, 800.0f, -500.0f)); g_pCamera->SetTargetPosition(&D3DXVECTOR3(0.0f, 800.0f, 0.0f)); g_pCamera->SetViewMatrix(); g_pCamera->SetProjectionMartix(); } void CreateTerrain() { g_pTerrian = new CTerrain(g_pDevice); g_pTerrian->LoadTerrainFromFile(TEXT("heighmap.raw"), TEXT("TerrainTexture.jpg")); g_pTerrian->InitTerrain(200, 200, 100.0f, 5.0f); } void CreateSkyBox() { g_pSkyBox = new CSkyBox(g_pDevice); g_pSkyBox->InitSkyBox(20000.0f); g_pSkyBox->InitSkyBoxTexture("skyfront.png", "skyback.png", "skyleft.png", "skyright.png", "skytop.png"); } void CreateParticle() { g_pParticle = new CParticle(g_pDevice); g_pParticle->InitParticle(); } void SetLight() { D3DLIGHT9 light; ::ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_DIRECTIONAL; light.Ambient = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); light.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); light.Specular = D3DXCOLOR(0.9f, 0.9f, 0.9f, 1.0f); light.Direction = D3DXVECTOR3(1.0f, 1.0f, 1.0f); g_pDevice->SetLight(0, &light); g_pDevice->LightEnable(0, true); g_pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, true); g_pDevice->SetRenderState(D3DRS_SPECULARENABLE, true); } void onInit() { //初始化D3D onCreatD3D(); //创建Mesh模型 CreateMesh(); //创建摄像机 CreateCamera(); //创建地形 CreateTerrain(); //创建天空盒 CreateSkyBox(); //创建粒子系统 CreateParticle(); //设置光照 SetLight(); } void onDestroy() { SAFE_DELETE(g_pDirectInput); SAFE_DELETE(g_pCamera); SAFE_DELETE(g_pTerrian); SAFE_DELETE(g_pSkyBox); SAFE_RELEASE(g_pDevice); SAFE_DELETE(g_pMesh1); SAFE_DELETE(g_pMesh2); SAFE_DELETE(g_pMesh3); } void onLogic(float fElapsedTime) { //使用DirectInput类读取数据 g_pDirectInput->GetInput(); // 沿摄像机各分量移动视角 if (g_pDirectInput->IsKeyDown(DIK_A)) g_pCamera->MoveAlongRightVec(-10.0f); if (g_pDirectInput->IsKeyDown(DIK_D)) g_pCamera->MoveAlongRightVec( 10.0f); if (g_pDirectInput->IsKeyDown(DIK_W)) g_pCamera->MoveAlongLookVec( 10.0f); if (g_pDirectInput->IsKeyDown(DIK_S)) g_pCamera->MoveAlongLookVec(-10.0f); if (g_pDirectInput->IsKeyDown(DIK_I)) g_pCamera->MoveAlongUpVec( 10.0f); if (g_pDirectInput->IsKeyDown(DIK_K)) g_pCamera->MoveAlongUpVec(-10.0f); //沿摄像机各分量旋转视角 if (g_pDirectInput->IsKeyDown(DIK_LEFT)) g_pCamera->RotationUpVec(-0.003f); if (g_pDirectInput->IsKeyDown(DIK_RIGHT)) g_pCamera->RotationUpVec( 0.003f); if (g_pDirectInput->IsKeyDown(DIK_UP)) g_pCamera->RotationRightVec(-0.003f); if (g_pDirectInput->IsKeyDown(DIK_DOWN)) g_pCamera->RotationRightVec( 0.003f); if (g_pDirectInput->IsKeyDown(DIK_J)) g_pCamera->RotationLookVec(-0.001f); if (g_pDirectInput->IsKeyDown(DIK_L)) g_pCamera->RotationLookVec( 0.001f); //鼠标控制右向量和上向量的旋转 //g_pCamera->RotationUpVec(g_pDirectInput->MouseDX()* 0.001f); //g_pCamera->RotationRightVec(g_pDirectInput->MouseDY() * 0.001f); //鼠标滚轮控制观察点收缩操作 static FLOAT fPosZ=0.0f; fPosZ += g_pDirectInput->MouseDZ()*3.0f; //计算并设置取景变换矩阵 D3DXMATRIX matView; g_pCamera->CalculateViewMatrix(&matView); g_pDevice->SetTransform(D3DTS_VIEW, &matView); //把正确的世界变换矩阵存到g_matWorld中 D3DXMatrixTranslation(&g_matWorld, 0.0f, 0.0f, fPosZ); //更新粒子系统 g_pParticle->UpdateParticle(fElapsedTime); } void onRender(float fElasedTime) { //前两个参数是0和NULL时,清空整个游戏窗口的内容(清的是后台) //第三个是清除的对象:前面表示清除颜色缓冲区,后面表示清除深度缓冲区,D3DCLEAR_STENCIL清空模板缓冲区 g_pDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,100,100), 1.0f, 0); g_pDevice->BeginScene(); D3DXMATRIX matWorld1, matWorld2, matWorld3, matWorldTerrain, matWorldSky; D3DXMatrixTranslation(&matWorld1, 0.0f, 800.0f, 0.0f); D3DXMatrixTranslation(&matWorld2, 0.0f, 1300.0f, 0.0f); D3DXMatrixTranslation(&matWorld3, -30.0f, 900.0f, -50.0f); D3DXMatrixTranslation(&matWorldTerrain, 0.0f, 0.0f, 0.0f); D3DXMatrixTranslation(&matWorldSky, 0.0f, -2000.0f, 0.0f); g_pMesh1->DrawMesh(matWorld1); g_pMesh2->DrawMesh(matWorld2); g_pMesh3->DrawMesh(matWorld3); g_pSkyBox->RenderSkyBox(&matWorldSky); g_pTerrian->RenderTerrain(&matWorldTerrain, false); g_pParticle->RenderParticle(); g_pDevice->EndScene(); g_pDevice->Present(NULL, NULL, NULL, NULL); } int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow){ UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: 在此放置代码。 MSG msg; HACCEL hAccelTable; // 初始化全局字符串 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_D3DDEMO, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // 执行应用程序初始化: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_D3DDEMO)); ZeroMemory(&msg, sizeof(msg)); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { static DWORD dwTime = timeGetTime(); DWORD dwCurrentTime = timeGetTime(); DWORD dwElapsedTime = dwCurrentTime - dwTime; float fElapsedTime = dwElapsedTime * 0.001f; //------------渲染和逻辑部分代码---------- onLogic(fElapsedTime); onRender(fElapsedTime); //----------------------------------------- if (dwElapsedTime < 1000 / 60) { Sleep(1000/ 60 - dwElapsedTime); } dwTime = dwCurrentTime; } } onDestroy(); return (int) msg.wParam; } // // 函数: MyRegisterClass() // // 目的: 注册窗口类。 // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_D3DDEMO)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_D3DDEMO); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // 函数: InitInstance(HINSTANCE, int) // // 目的: 保存实例句柄并创建主窗口 // // 注释: // // 在此函数中,我们在全局变量中保存实例句柄并 // 创建和显示主程序窗口。 // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // 将实例句柄存储在全局变量中 g_hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!g_hWnd) { return FALSE; } //初始化DirectInput类 g_pDirectInput = new CDirectInput(); g_pDirectInput->Init(g_hWnd, hInst, DISCL_FOREGROUND|DISCL_NONEXCLUSIVE, DISCL_FOREGROUND|DISCL_NONEXCLUSIVE); SetMenu(g_hWnd, NULL); ShowWindow(g_hWnd, nCmdShow); UpdateWindow(g_hWnd); onInit(); return TRUE; } // // 函数: WndProc(HWND, UINT, WPARAM, LPARAM) // // 目的: 处理主窗口的消息。 // // WM_COMMAND - 处理应用程序菜单 // WM_PAINT - 绘制主窗口 // WM_DESTROY - 发送退出消息并返回 // // LRESULT CALLBACK WndProc(HWND g_hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_KEYDOWN: if (wParam == VK_ESCAPE) PostQuitMessage(0); break; case WM_CLOSE: DestroyWindow(g_hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(g_hWnd, message, wParam, lParam); } return 0; }