void CTestGame::Init() { CGame::Init(); SetCaption("Test Game"); mouse->SetVisible(false); //create game space SDL_Rect bounds; bounds.x = 0; bounds.y = 0; bounds.w = GetScreenWidth(); bounds.h = GetScreenHeight(); space = new CEntitySpace(bounds); //create entity CSurface* surf = CSurface::Load("smile.png"); surf->SetColorKey(255,0,106); entity = new CEntity(surf,10.0,false); entity->position.x = entity->GetWidth()/2; entity->position.y = entity->GetHeight()/2; space->Add(entity); //create segments seg = new CSegment(SDL_MapRGB(Display_Surface->GetSDLSurface()->format, 0,0,0)); seg->v1.x = 0; seg->v1.y = 500; seg->v2.x = 500; seg->v2.y = 500; space->Add(seg); }
BOOL GetPointColor(SPickQuery::SResult* R, u32& alpha) { CSurface* surf = R->e_mesh->GetSurfaceByFaceID(R->tag); VERIFY(surf); Shader_xrLC* c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); if (!c_sh->flags.bRendering) return FALSE; const Fvector2* cuv[3]; R->e_mesh->GetFaceTC (R->tag,cuv); // barycentric coords // note: W,U,V order Fvector B; B.set (1.0f - R->u - R->v,R->u,R->v); // calc UV Fvector2 uv; uv.x = cuv[0]->x*B.x + cuv[1]->x*B.y + cuv[2]->x*B.z; uv.y = cuv[0]->y*B.x + cuv[1]->y*B.y + cuv[2]->y*B.z; int U = iFloor(uv.x*float(surf->m_ImageData->w) + .5f); int V = iFloor(uv.y*float(surf->m_ImageData->h)+ .5f); U %= surf->m_ImageData->w; if (U<0) U+=surf->m_ImageData->w; V %= surf->m_ImageData->h; if (V<0) V+=surf->m_ImageData->h; alpha = color_get_A(surf->m_ImageData->layers.back()[V*surf->m_ImageData->w+U]); return TRUE; }
void EDetail::Export(IWriter& F, LPCSTR tex_name, const Fvector2& offs, const Fvector2& scale, bool rot) { R_ASSERT (m_pRefs); CSurface* surf = *m_pRefs->FirstSurface(); R_ASSERT (surf); // write data F.w_stringZ (surf->_ShaderName()); F.w_stringZ (tex_name);//surf->_Texture()); F.w_u32 (m_Flags.get()); F.w_float (m_fMinScale); F.w_float (m_fMaxScale); F.w_u32 (number_vertices); F.w_u32 (number_indices); // remap UV EVertexIn* rm_vertices = xr_alloc<EVertexIn>(number_vertices); for (u32 k=0; k<number_vertices; k++) rm_vertices[k].remapUV(vertices[k],offs,scale,rot); F.w (rm_vertices, number_vertices*sizeof(fvfVertexIn)); F.w (indices, number_indices*sizeof(WORD)); xr_free (rm_vertices); }
//---------------------------------------------------- IC bool build_mesh(const Fmatrix& parent, CEditableMesh* mesh, CGeomPartExtractor* extractor, u32 game_mtl_mask, BOOL ignore_shader) { bool bResult = true; mesh->GenerateVNormals (&parent); // fill faces for (SurfFaces::const_iterator sp_it=mesh->GetSurfFaces().begin(); sp_it!=mesh->GetSurfFaces().end(); sp_it++){ const IntVec& face_lst = sp_it->second; CSurface* surf = sp_it->first; int gm_id = surf->_GameMtl(); if (gm_id==GAMEMTL_NONE_ID){ ELog.DlgMsg (mtError,"Object '%s', surface '%s' contain invalid game material.",mesh->Parent()->m_LibName.c_str(),surf->_Name()); bResult = FALSE; break; } SGameMtl* M = GMLib.GetMaterialByID(gm_id); if (0==M){ ELog.DlgMsg (mtError,"Object '%s', surface '%s' contain undefined game material.",mesh->Parent()->m_LibName.c_str(),surf->_Name()); bResult = FALSE; break; } if (!M->Flags.is(game_mtl_mask)) continue; // check engine shader compatibility if (!ignore_shader){ IBlender* B = EDevice.Resources->_FindBlender(surf->_ShaderName()); if (FALSE==B){ ELog.Msg (mtError,"Can't find engine shader '%s'. Object '%s', surface '%s'. Export interrupted.",surf->_ShaderName(),mesh->Parent()->m_LibName.c_str(),surf->_Name()); bResult = FALSE; break; } if (TRUE==B->canBeLMAPped()){ ELog.Msg (mtError,"Object '%s', surface '%s' contain static engine shader - '%s'. Export interrupted.",mesh->Parent()->m_LibName.c_str(),surf->_Name(),surf->_ShaderName()); bResult = FALSE; break; } } const st_Face* faces = mesh->GetFaces(); VERIFY(faces); const Fvector* vn = mesh->GetVNormals(); VERIFY(vn); const Fvector* pts = mesh->GetVertices(); VERIFY(pts); for (IntVec::const_iterator f_it=face_lst.begin(); f_it!=face_lst.end(); f_it++){ const st_Face& face = faces[*f_it]; Fvector v[3],n[3]; parent.transform_tiny (v[0],pts[face.pv[0].pindex]); parent.transform_tiny (v[1],pts[face.pv[1].pindex]); parent.transform_tiny (v[2],pts[face.pv[2].pindex]); parent.transform_dir (n[0],vn[*f_it*3+0]); n[0].normalize(); parent.transform_dir (n[1],vn[*f_it*3+1]); n[1].normalize(); parent.transform_dir (n[2],vn[*f_it*3+2]); n[2].normalize(); const Fvector2* uv[3]; mesh->GetFaceTC (*f_it,uv); extractor->AppendFace (surf,v,n,uv); } if (!bResult) break; } mesh->UnloadVNormals (); return bResult; }
void EDetail::OnDeviceCreate() { if (!m_pRefs) return; CSurface* surf = *m_pRefs->FirstSurface(); VERIFY (surf); AnsiString s_name = surf->_ShaderName(); AnsiString t_name = surf->_Texture(); shader.create (s_name.c_str(),t_name.c_str()); }
// static creation methods // creates object, calls second-phase, leaves on stack CSurface* CSurface::NewLC(RWsSession& arWs, TInt aW, TInt aH, TInt aBpp) { // allocate object on heap CSurface* newobj = new (ELeave) CSurface(); // put on cleanup stack CleanupStack::PushL(newobj); // call second-phase constructor newobj->ConstructL(arWs, aW, aH, aBpp); return(newobj); }
bool SceneBuilder::BuildSOMModel() { BOOL bResult = TRUE; CMemoryWriter F; F.open_chunk (0); F.w_u32 (0); F.close_chunk (); F.open_chunk (1); ObjectList& lst = Scene->ListObj(OBJCLASS_SCENEOBJECT); for (ObjectIt it=lst.begin(); it!=lst.end(); it++){ CSceneObject* S = (CSceneObject*)(*it); CEditableObject* E = S->GetReference(); R_ASSERT(E); if (E->m_Flags.is(CEditableObject::eoSoundOccluder)){ Fvector v; const Fmatrix& parent = S->_Transform(); for (EditMeshIt m_it=E->FirstMesh(); m_it!=E->LastMesh(); m_it++){ for (SurfFacesPairIt sf_it=(*m_it)->m_SurfFaces.begin(); sf_it!=(*m_it)->m_SurfFaces.end(); sf_it++){ CSurface* surf = sf_it->first; int gm_id = surf->_GameMtl(); if (gm_id==GAMEMTL_NONE_ID){ ELog.DlgMsg (mtError,"Object '%s', surface '%s' contain invalid game material.",(*m_it)->Parent()->m_LibName.c_str(),surf->_Name()); bResult = FALSE; break; } SGameMtl* mtl = GMLib.GetMaterialByID(gm_id); if (0==mtl){ ELog.DlgMsg (mtError,"Object '%s', surface '%s' contain undefined game material.",(*m_it)->Parent()->m_LibName.c_str(),surf->_Name()); bResult = FALSE; break; } BOOL b2Sided = surf->m_Flags.is(CSurface::sf2Sided); IntVec& i_lst = sf_it->second; for (IntIt i_it=i_lst.begin(); i_it!=i_lst.end(); i_it++){ st_Face& face = (*m_it)->m_Faces[*i_it]; for (int k=0; k<3; k++){ parent.transform_tiny(v,(*m_it)->m_Verts[face.pv[k].pindex]); F.w_fvector3(v); } F.w_u32 (b2Sided); F.w_float (mtl->fSndOcclusionFactor); } } } } } BOOL bValid = !!F.chunk_size()&&bResult; F.close_chunk(); if (bValid){ xr_string som_name = MakeLevelPath("level.som"); bValid = F.save_to(som_name.c_str()); } return bValid; }
CSurface* CEditableObject::CreateSurface(LPCSTR m_name, SXRShaderData& d) { CSurface* S = FindSurfaceByName(m_name); if (!S){ S = new CSurface(); S->SetName (m_name); if (!ParseMAMaterial(S,d)){ xr_delete(S); return 0; } m_Surfaces.push_back(S); } return S; }
bool EDetailManager::GetSummaryInfo(SSceneSummary* inf) { for (DetailIt it=objects.begin(); it!=objects.end(); it++){ ((EDetail*)(*it))->OnDeviceCreate(); CEditableObject* E = ((EDetail*)(*it))->m_pRefs; if (!E) continue; CSurface* surf = *E->FirstSurface(); VERIFY(surf); inf->AppendTexture (surf->_Texture(),SSceneSummary::sttDO,0,0,"$DETAILS$"); } return true; }
void CStatBox::Draw(CSurface* display,int x,int y) { CSurface* line; int drawy = y; for(int i = 0; i<lines->size(); i++) { line = lines->at(i); if(line != NULL) { line->Draw(display,x,drawy); drawy += line->GetHeight() + STATBOX_LINE_PADDING; } } }
void EDetail::Export(LPCSTR name) { CSurface* surf = *m_pRefs->FirstSurface(); R_ASSERT (surf); IWriter* F = FS.w_open(name); if (F){ Fvector2 offs = {0,0}; Fvector2 scale = {1,1}; Export (*F,surf->_Texture(),offs,scale,false); FS.w_close (F); }else{ Log ("!Can't export detail:",name); } }
void CEglTest_TestStep_StressLoad::LoadGpuProcessorL() { CSurface *surface = CSurface::SurfaceFactoryL(ESurfTypeEglWindow); CleanupStack::PushL(surface); surface->CreateL(EStandard128sqSurface, TPoint(128, 128)); TRgb bg = TRgb(0x55, 0x88, 0xff); // Cyan/turqoise-ish. TRgb fg = TRgb(0xff, 0x11, 0x22); // Red (sort of) while(!__e32_atomic_load_acq32(&iStopThreadFlag[EThreadLoadGpuProcessor])) { surface->DrawContentL(bg); surface->DrawComplexL(fg); surface->SubmitContent(ETrue); } CleanupStack::PopAndDestroy(surface); eglReleaseThread(); }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- HRESULT CDisplay::ShowBitmap( HBITMAP hbm, LPDIRECTDRAWPALETTE pPalette ) { if( NULL == m_pddsFrontBuffer || NULL == m_pddsBackBuffer ) return E_POINTER; // Set the palette before loading the bitmap if( pPalette ) m_pddsFrontBuffer->SetPalette( pPalette ); CSurface backBuffer; backBuffer.Create( m_pddsBackBuffer ); if( FAILED( backBuffer.DrawBitmap( hbm, 0, 0, 0, 0 ) ) ) return E_FAIL; return Present(); }
int CStatBox::CalcHeight() { //find sum of line heights, plus padding int height = 0; CSurface* line; for(int i = 0; i<lines->size(); i++) { line = lines->at(i); if(line != NULL) { height += line->GetHeight(); } } height += (lines->size() - 1) * STATBOX_LINE_PADDING; return height; }
void CEglTest_TestStep_StressLoad::LoadGpuMemoryL() { const TInt KMaxSurfaceAllocs = 1000; CSurface **surfaces = new CSurface*[KMaxSurfaceAllocs]; ENGINE_ASSERT(surfaces); TInt nSurfaces = 0; TInt err; while(!__e32_atomic_load_acq32(&iStopThreadFlag[EThreadLoadGpuMemory])) { ENGINE_ASSERT(nSurfaces < KMaxSurfaceAllocs); CSurface* s = CSurface::SurfaceFactoryL(ESurfTypePBuffer); if (s) { TRAP(err, s->CreateL(ELargeSurface)); if (err == KErrNone) { surfaces[nSurfaces++] = s; TRAP(err, s->DrawContentL(TRgb(0x10, 0x20, 0xB0))); } else { delete s; s = NULL; } } if (!s) { User::After(100 * 1000); TInt nRelease = nSurfaces / 4; for(TInt i = 0; i < nRelease; i++) { delete surfaces[--nSurfaces]; surfaces[nSurfaces] = NULL; } User::After(100 * 1000); // 100 ms. } } while(nSurfaces) { delete surfaces[--nSurfaces]; } delete [] surfaces; eglReleaseThread(); }
void Font::Render(const string &str, int x, int y, dword height, dword style, D3DXCOLOR color, int maxWidth, bool fade, Align alignment) { CSurface texture; RenderToTexture(texture, str, height, style, color, maxWidth, fade); if (alignment != Left) { word *wcBuf = StringToWChar(str); dword dwRequiredWidth; m_pFont->GetTextExtent(wcBuf, -1, &dwRequiredWidth); delete [] wcBuf; if (alignment == Center) x -= (dwRequiredWidth / 2); else if (alignment == Right) x -= dwRequiredWidth; } texture.Render(x, y); }
int CStatBox::CalcWidth() { //find longest line of text int length = 0; int longest = 0; CSurface* line; for(int i = 0; i<lines->size(); i++) { line = lines->at(i); if(line != NULL) { length = line->GetWidth(); if(length > longest) { longest = length; } } } return longest; }
void Creeping:: init() { DEBUG_PRINT_LINE; deinit(); font_render = new FontRender(conf.get_conf()); std::vector<std::string> text; std::string logo; MessageReader mr; mr.make(conf.get_conf()->lineText, conf.get_conf()->bRss, &text, &logo); std::vector<std::string>::iterator i; for (i = text.begin(); i != text.end(); i++) { CSurface * surf = new_surface(wnd); surf->set_tex_color(conf.get_conf()->window.clForeground); surf->set_text( &(*i), font_render); } if(!logo.empty()) { CSurface * surf = new_surface(wnd); surf->set_image(&logo); surf->as_logo(); } DEBUG_PRINT_LINE; }
bool CTgaWriter::Write(const std::string& fileName, CSurface& surface) { m_FileName=fileName; //file = IGenericFile::Open(fileName.c_str(), IGenericFile::OPEN_READ | IGenericFile::OPEN_BINARY | IGenericFile::OPEN_STANDALONE, false, true); m_File.open(fileName.c_str(),std::ios::out|std::ios::binary); if(!m_File)return false; memset(&m_Header,0,sizeof(m_Header)); m_Header.Width=surface.GetWidth(); m_Header.Height=surface.GetHeight(); m_Header.Bits=surface.GetDepth()<<3; if(surface.GetFormat()==CSurface::EFormat_A8R8G8B8 || surface.GetFormat()==CSurface::EFormat_R8G8B8 || surface.GetFormat()==CSurface::EFormat_X8R8G8B8){ m_Header.ImageType=2; }else if(surface.GetFormat()==CSurface::EFormat_S8){ m_Header.ImageType=3; } // Write header m_Header.Write(m_File); if(!m_File)return false; // Write data m_File.write((char*)surface.GetDataPointer(),surface.GetSize()); // Close and bail out if(!m_File)return false; m_File.close(); return true; }
bool CEditableMesh::LoadMesh(IReader& F){ u32 version=0; R_ASSERT(F.r_chunk(EMESH_CHUNK_VERSION,&version)); if (version!=EMESH_CURRENT_VERSION){ ELog.DlgMsg( mtError, "CEditableMesh: unsuported file version. Mesh can't load."); return false; } R_ASSERT(F.find_chunk(EMESH_CHUNK_MESHNAME)); F.r_stringZ (m_Name); R_ASSERT(F.r_chunk(EMESH_CHUNK_BBOX,&m_Box)); R_ASSERT(F.r_chunk(EMESH_CHUNK_FLAGS,&m_Flags)); F.r_chunk(EMESH_CHUNK_BOP,&m_Ops); R_ASSERT(F.find_chunk(EMESH_CHUNK_VERTS)); m_VertCount = F.r_u32(); if (m_VertCount<3){ Log ("!CEditableMesh: Vertices<3."); return false; } m_Verts = xr_alloc<Fvector>(m_VertCount); F.r (m_Verts, m_VertCount*sizeof(Fvector)); R_ASSERT(F.find_chunk(EMESH_CHUNK_FACES)); m_FaceCount = F.r_u32(); m_Faces = xr_alloc<st_Face>(m_FaceCount); if (m_FaceCount==0){ Log ("!CEditableMesh: Faces==0."); return false; } F.r (m_Faces, m_FaceCount*sizeof(st_Face)); m_SGs = xr_alloc<u32>(m_FaceCount); Memory.mem_fill32 (m_SGs,m_Flags.is(flSGMask)?0:u32(-1),m_FaceCount); u32 sg_chunk_size = F.find_chunk(EMESH_CHUNK_SG); if (sg_chunk_size){ VERIFY (m_FaceCount*sizeof(u32)==sg_chunk_size); F.r (m_SGs, m_FaceCount*sizeof(u32)); } R_ASSERT(F.find_chunk(EMESH_CHUNK_VMREFS)); m_VMRefs.resize (F.r_u32()); int sz_vmpt = sizeof(st_VMapPt); for (VMRefsIt r_it=m_VMRefs.begin(); r_it!=m_VMRefs.end(); r_it++){ r_it->count = F.r_u8(); r_it->pts = xr_alloc<st_VMapPt>(r_it->count); F.r (r_it->pts, sz_vmpt*r_it->count); } R_ASSERT(F.find_chunk(EMESH_CHUNK_SFACE)); string128 surf_name; u32 sface_cnt = F.r_u16(); // surface-face count for (u32 sp_i=0; sp_i<sface_cnt; sp_i++){ F.r_stringZ (surf_name,sizeof(surf_name)); int surf_id; CSurface* surf = m_Parent->FindSurfaceByName(surf_name, &surf_id); VERIFY(surf); IntVec& face_lst = m_SurfFaces[surf]; face_lst.resize (F.r_u32()); if (face_lst.empty()){ Log ("!Empty surface found: %s",surf->_Name()); return false; } F.r (&*face_lst.begin(), face_lst.size()*sizeof(int)); std::sort (face_lst.begin(),face_lst.end()); } if(F.find_chunk(EMESH_CHUNK_VMAPS_2)){ m_VMaps.resize (F.r_u32()); for (VMapIt vm_it=m_VMaps.begin(); vm_it!=m_VMaps.end(); vm_it++){ *vm_it = xr_new<st_VMap>(); F.r_stringZ ((*vm_it)->name); (*vm_it)->dim = F.r_u8(); (*vm_it)->polymap=F.r_u8(); (*vm_it)->type = F.r_u8(); (*vm_it)->resize(F.r_u32()); F.r ((*vm_it)->getVMdata(), (*vm_it)->VMdatasize()); F.r ((*vm_it)->getVIdata(), (*vm_it)->VIdatasize()); if ((*vm_it)->polymap) F.r ((*vm_it)->getPIdata(), (*vm_it)->PIdatasize()); } }else{ if(F.find_chunk(EMESH_CHUNK_VMAPS_1)){ m_VMaps.resize (F.r_u32()); for (VMapIt vm_it=m_VMaps.begin(); vm_it!=m_VMaps.end(); vm_it++){ *vm_it = xr_new<st_VMap>(); F.r_stringZ ((*vm_it)->name); (*vm_it)->dim = F.r_u8(); (*vm_it)->type = F.r_u8(); (*vm_it)->resize(F.r_u32()); F.r ((*vm_it)->getVMdata(), (*vm_it)->VMdatasize() ); } }else{ R_ASSERT(F.find_chunk(EMESH_CHUNK_VMAPS_0)); m_VMaps.resize (F.r_u32()); for (VMapIt vm_it=m_VMaps.begin(); vm_it!=m_VMaps.end(); vm_it++){ *vm_it = xr_new<st_VMap>(); F.r_stringZ ((*vm_it)->name); (*vm_it)->dim = 2; (*vm_it)->type = vmtUV; (*vm_it)->resize(F.r_u32()); F.r ((*vm_it)->getVMdata(), (*vm_it)->VMdatasize() ); } } // update vmaps RebuildVMaps(); } #ifdef _EDITOR if (!EPrefs->object_flags.is(epoDeffLoadRB)){ GenerateFNormals (); GenerateAdjacency (); GenerateVNormals (); GenerateRenderBuffers(); UnloadFNormals (); UnloadAdjacency (); UnloadVNormals (); } if (!EPrefs->object_flags.is(epoDeffLoadCF)) GenerateCFModel(); #endif Optimize(false); RebuildVMaps(); return true; }
void * Creeping:: redraw_window(void * _this) { DEBUG_PRINT_LINE; Creeping * self = (Creeping *) _this; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); pthread_cleanup_push(&Creeping::exit_redraw_window, _this); int current_pos = 0; int window_x, window_y, window_width, window_height; self->mutex.lock(); CTimer timer; timer.set_interval(1000000/self->conf.get_conf()->ScrollingSpeed); self->wnd->open(&self->conf); self->wnd->get_current_rect(&window_x, &window_y, &window_width, &window_height); self->init(); self->wnd->draw(); timer.start(); self->mutex.unlock(); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); for(;;) { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); self->mutex.lock(); self->wnd->clear(); CSurface * logo = self->wnd->get_logo(); std::vector<CSurface*> * surfaces = self->wnd->get_surfaces(); std::vector<CSurface*>::iterator i = surfaces->begin(); current_pos = timer.get_val(); int length = window_width - current_pos; if(!surfaces->empty() && (current_pos - (*i)->get_width()) > window_width) { timer.offset( (*i)->get_width()); length += (*i)->get_width(); delete (*i); surfaces = self->wnd->get_surfaces(); } for (i = surfaces->begin(); i != surfaces->end(); i++) { (*i)->draw(length); length += (*i)->get_width() ; if(length > window_width) break; } if(logo != NULL) logo->draw(0); self->wnd->draw(); self->mutex.unlock(); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_testcancel(); if(surfaces->empty() && self->is_once) pthread_exit(NULL); if(surfaces->empty() && self->is_once == false) { self->init(); timer.set_val(0); } } pthread_cleanup_pop(0); DEBUG_PRINT_LINE; }
bool CEditableObject::Import_LWO(const char* fn, bool bNeedOptimize) { lwObject *I=0; // UI->SetStatus("Importing..."); // UI->ProgressStart(100,"Read file:"); // UI->ProgressUpdate(1); string512 fname; strcpy(fname,fn); #ifdef _EDITOR I=LWO_ImportObject(fname,I); #else unsigned int failID; int failpos; I = lwGetObject( fname, &failID, &failpos ); #endif // UI->ProgressUpdate(100); if (I){ bool bResult=true; ELog.Msg( mtInformation, "CEditableObject: import lwo %s...", fname ); // parse lwo object { m_Meshes.reserve (I->nlayers); m_Surfaces.reserve (I->nsurfs); // surfaces st_lwSurface* Isf=0; { int i=0; // UI->ProgressStart(I->nsurfs,"Check surf:"); for (Isf=I->surf; Isf; Isf=Isf->next){ // UI->ProgressUpdate(i); Isf->alpha_mode=i; // перетираем для внутренних целей !!! CSurface* Osf = new CSurface(); m_Surfaces.push_back(Osf); if (Isf->name&&Isf->name[0]) Osf->SetName(Isf->name); else Osf->SetName("Default"); Osf->m_Flags.set(CSurface::sf2Sided,(Isf->sideflags==3)?TRUE:FALSE); AnsiString en_name="default", lc_name="default", gm_name="default"; XRShader* sh_info = 0; if (Isf->nshaders&&(stricmp(Isf->shader->name,SH_PLUGIN_NAME)==0)){ sh_info = (XRShader*)Isf->shader->data; en_name = sh_info->en_name; lc_name = sh_info->lc_name; gm_name = sh_info->gm_name; }else ELog.Msg(mtError,"CEditableObject: Shader not found on surface '%s'.",Osf->_Name()); #ifdef _EDITOR if (!Device.Resources->_FindBlender(en_name.c_str())){ ELog.Msg(mtError,"CEditableObject: Render shader '%s' - can't find in library.\nUsing 'default' shader on surface '%s'.", en_name.c_str(), Osf->_Name()); en_name = "default"; } if (!Device.ShaderXRLC.Get(lc_name.c_str())){ ELog.Msg(mtError,"CEditableObject: Compiler shader '%s' - can't find in library.\nUsing 'default' shader on surface '%s'.", lc_name.c_str(), Osf->_Name()); lc_name = "default"; } if (!GMLib.GetMaterial(gm_name.c_str())){ ELog.Msg(mtError,"CEditableObject: Game material '%s' - can't find in library.\nUsing 'default' material on surface '%s'.", lc_name.c_str(), Osf->_Name()); gm_name = "default"; } #endif // fill texture layers int cidx; st_lwClip* Icl; u32 dwNumTextures=0; for (st_lwTexture* Itx=Isf->color.tex; Itx; Itx=Itx->next){ string1024 tname=""; dwNumTextures++; cidx = -1; if (Itx->type==ID_IMAP) cidx=Itx->param.imap.cindex; else{ ELog.DlgMsg(mtError, "Import LWO (Surface '%s'): 'Texture' is not Image Map!",Osf->_Name()); bResult=false; break; } if (cidx!=-1){ // get textures for (Icl=I->clip; Icl; Icl=Icl->next) if ((cidx==Icl->index)&&(Icl->type==ID_STIL)){ strcpy(tname,Icl->source.still.name); break; } if (tname[0]==0){ ELog.DlgMsg(mtError, "Import LWO (Surface '%s'): 'Texture' name is empty or non 'STIL' type!",Osf->_Name()); bResult=false; break; } string256 tex_name; _splitpath( tname, 0, 0, tex_name, 0 ); Osf->SetTexture(EFS.AppendFolderToName(tex_name,1,TRUE)); // get vmap refs Osf->SetVMap(Itx->param.imap.vmap_name); } } if (!bResult) break; if (!Osf->_VMap()||!Osf->_VMap()[0]){ ELog.DlgMsg(mtError, "Invalid surface '%s'. VMap empty.",Osf->_Name()); bResult = false; break; } if (!Osf->_Texture()||!Osf->_Texture()[0]){ ELog.DlgMsg(mtError, "Can't create shader. Invalid surface '%s'. Textures empty.",Osf->_Name()); bResult = false; break; } if (en_name.c_str()==0){ ELog.DlgMsg(mtError, "Can't create shader. Invalid surface '%s'. Shader empty.",Osf->_Name()); bResult = false; break; } Osf->SetShader (en_name.c_str()); Osf->SetShaderXRLC (lc_name.c_str()); Osf->SetGameMtl (gm_name.c_str()); Osf->SetFVF (D3DFVF_XYZ|D3DFVF_NORMAL|(dwNumTextures<<D3DFVF_TEXCOUNT_SHIFT)); i++; } } if (bResult){ // mesh layers st_lwLayer* Ilr=0; int k=0; for (Ilr=I->layer; Ilr; Ilr=Ilr->next){ // create new mesh CEditableMesh* MESH= new CEditableMesh(this); m_Meshes.push_back(MESH); if (Ilr->name) MESH->SetName(Ilr->name); else MESH->SetName(""); MESH->m_Box.set(Ilr->bbox[0],Ilr->bbox[1],Ilr->bbox[2], Ilr->bbox[3],Ilr->bbox[4],Ilr->bbox[5]); // parse mesh(lwo-layer) data // vmaps st_lwVMap* Ivmap=0; int vmap_count=0; if (Ilr->nvmaps==0){ ELog.DlgMsg(mtError, "Import LWO: Mesh layer must contain UV!"); bResult=false; break; } // индексы соответствия импортируемых мап static VMIndexLink VMIndices; VMIndices.clear(); for (Ivmap=Ilr->vmap; Ivmap; Ivmap=Ivmap->next){ switch(Ivmap->type){ case ID_TXUV:{ if (Ivmap->dim!=2){ ELog.DlgMsg(mtError, "Import LWO: 'UV Map' must contain 2 value!"); bResult=false; break; } MESH->m_VMaps.push_back(new st_VMap(Ivmap->name,vmtUV,!!Ivmap->perpoly)); st_VMap* Mvmap=MESH->m_VMaps.back(); int vcnt=Ivmap->nverts; // VMap Mvmap->copyfrom(*Ivmap->val,vcnt); // flip uv for (int k=0; k<Mvmap->size(); k++){ Fvector2& uv = Mvmap->getUV(k); uv.y=1.f-uv.y; } // vmap index VMIndices[Ivmap] = vmap_count++; }break; case ID_WGHT:{ if (Ivmap->dim!=1){ ELog.DlgMsg(mtError, "Import LWO: 'Weight' must contain 1 value!"); bResult=false; break; } MESH->m_VMaps.push_back(new st_VMap(Ivmap->name,vmtWeight,false)); st_VMap* Mvmap=MESH->m_VMaps.back(); int vcnt=Ivmap->nverts; // VMap Mvmap->copyfrom(*Ivmap->val,vcnt); // vmap index VMIndices[Ivmap] = vmap_count++; }break; case ID_PICK: ELog.Msg(mtError,"Found 'PICK' VMAP. Import failed."); bResult = false; break; case ID_MNVW: ELog.Msg(mtError,"Found 'MNVW' VMAP. Import failed."); bResult = false; break; case ID_MORF: ELog.Msg(mtError,"Found 'MORF' VMAP. Import failed."); bResult = false; break; case ID_SPOT: ELog.Msg(mtError,"Found 'SPOT' VMAP. Import failed."); bResult = false; break; case ID_RGB: ELog.Msg(mtError,"Found 'RGB' VMAP. Import failed."); bResult = false; break; case ID_RGBA: ELog.Msg(mtError,"Found 'RGBA' VMAP. Import failed."); bResult = false; break; } if (!bResult) break; } if (!bResult) break; // points // UI->ProgressStart(Ilr->point.count,"Fill points:"); { MESH->m_VertCount = Ilr->point.count; MESH->m_Vertices = xr_alloc<Fvector>(MESH->m_VertCount); int id = Ilr->polygon.count/50; if (id==0) id = 1; for (int i=0; i<Ilr->point.count; ++i) { st_lwPoint& Ipt = Ilr->point.pt[i]; Fvector& Mpt = MESH->m_Vertices[i]; Mpt.set (Ipt.pos); } } if (!bResult) break; // polygons MESH->m_FaceCount = Ilr->polygon.count; MESH->m_Faces = xr_alloc<st_Face>(MESH->m_FaceCount); MESH->m_SmoothGroups = xr_alloc<u32>(MESH->m_FaceCount); Memory.mem_fill32 (MESH->m_SmoothGroups,u32(-1),MESH->m_FaceCount); MESH->m_VMRefs.reserve (Ilr->polygon.count*3); IntVec surf_ids; surf_ids.resize(Ilr->polygon.count); int id = Ilr->polygon.count/50; if (id==0) id = 1; for (int i=0; i<Ilr->polygon.count; ++i) { st_Face& Mpol=MESH->m_Faces[i]; st_lwPolygon& Ipol=Ilr->polygon.pol[i]; if (Ipol.nverts!=3) { ELog.DlgMsg(mtError, "Import LWO: Face must contain only 3 vertices!"); bResult=false; break; } for (int pv_i=0; pv_i<3; ++pv_i) { st_lwPolVert& Ipv=Ipol.v[pv_i]; st_FaceVert& Mpv=Mpol.pv[pv_i]; Mpv.pindex =Ipv.index; MESH->m_VMRefs.push_back(st_VMapPtLst()); st_VMapPtLst& m_vm_lst = MESH->m_VMRefs.back(); DEFINE_VECTOR (st_VMapPt,VMapPtVec,VMapPtIt); VMapPtVec vm_lst; Mpv.vmref = MESH->m_VMRefs.size()-1; // parse uv-map int vmpl_cnt =Ipv.nvmaps; st_lwPoint& Ipt =Ilr->point.pt[Mpv.pindex]; int vmpt_cnt =Ipt.nvmaps; if (!vmpl_cnt&&!vmpt_cnt){ ELog.DlgMsg (mtError,"Found mesh without UV's!",0); bResult = false; break; } AStringVec names; if (vmpl_cnt){ // берем из poly for (int vm_i=0; vm_i<vmpl_cnt; vm_i++){ if (Ipv.vm[vm_i].vmap->type!=ID_TXUV) continue; vm_lst.push_back(st_VMapPt()); st_VMapPt& pt = vm_lst.back(); pt.vmap_index = VMIndices[Ipv.vm[vm_i].vmap];// номер моей VMap names.push_back (Ipv.vm[vm_i].vmap->name); pt.index = Ipv.vm[vm_i].index; } } if (vmpt_cnt){ // берем из points for (int vm_i=0; vm_i<vmpt_cnt; vm_i++){ if (Ipt.vm[vm_i].vmap->type!=ID_TXUV) continue; if (std::find(names.begin(),names.end(),Ipt.vm[vm_i].vmap->name)!=names.end()) continue; vm_lst.push_back(st_VMapPt()); st_VMapPt& pt = vm_lst.back(); pt.vmap_index = VMIndices[Ipt.vm[vm_i].vmap]; // номер моей VMap pt.index = Ipt.vm[vm_i].index; } } std::sort(vm_lst.begin(),vm_lst.end(),CompareFunc); // parse weight-map int vm_cnt =Ipt.nvmaps; for (int vm_i=0; vm_i<vm_cnt; vm_i++){ if (Ipt.vm[vm_i].vmap->type!=ID_WGHT) continue; vm_lst.push_back(st_VMapPt()); st_VMapPt& pt = vm_lst.back(); pt.vmap_index = VMIndices[Ipt.vm[vm_i].vmap]; // номер моей VMap pt.index = Ipt.vm[vm_i].index; } m_vm_lst.count = vm_lst.size(); m_vm_lst.pts = xr_alloc<st_VMapPt>(m_vm_lst.count); Memory.mem_copy (m_vm_lst.pts,&*vm_lst.begin(),m_vm_lst.count*sizeof(st_VMapPt)); } if (!bResult) break; // Ipol.surf->alpha_mode - заполнено как номер моего surface surf_ids[i] = Ipol.surf->alpha_mode; } if (!bResult) break; for (u32 pl_id=0; pl_id<MESH->GetFCount(); pl_id++) MESH->m_SurfFaces[m_Surfaces[surf_ids[pl_id]]].push_back(pl_id); if (!bResult) break; k++; //MESH->DumpAdjacency(); if (bNeedOptimize) MESH->OptimizeMesh(false); //MESH->DumpAdjacency(); MESH->RebuildVMaps(); // !!!!!! } } } #ifdef _EDITOR LWO_CloseFile(I); #else lwFreeObject(I); #endif // UI->ProgressEnd(); // UI->SetStatus(""); if (bResult) VerifyMeshNames(); else ELog.DlgMsg(mtError,"Can't parse LWO object."); if (bResult) m_LoadName = (strext(fname))? strcpy(strext(fname),".object"):strcat(strext(fname),".object"); return bResult; }else ELog.DlgMsg(mtError,"Can't import LWO object file."); // UI->ProgressEnd(); // UI->SetStatus(""); return false; }
int main(int argc, char *argv[]) { init(); //init SDL g_CWindow.SSurface = SDL_SetVideoMode( WIDTH , HEIGHT , 32 , SDL_DOUBLEBUF|SDL_HWSURFACE|SDL_ANYFORMAT); //assign surface g_pCMenu = MD2Model::load("menu.md2"); g_SPlayer.pCModel = MD2Model::load("player.md2"); g_SPlayer.pCLaser = MD2Model::load("laser.md2"); g_pCLoop = MD2Model::load("loop.md2"); Uint32 u32Start; while (g_bRunning) { u32Start = SDL_GetTicks(); //Get the tick this cycle started on if(g_dAngle>360) g_dAngle = 0; if(g_dAngle < 0 ) g_dAngle = 360; control(); //get user input if(!g_bStart) draw_menu(); //Draw 'Seizure Ships! else if(!lost) game(); //Update game status else lose(); if(!lost) { if(g_bThreadVisualization) { //Shows triangles drawn by each thread g_CWindow.draw_text("Work thread 1",0,24*2,RED); g_CWindow.draw_text("Work thread 2",0,24*3,GREEN); g_CWindow.draw_text("Work thread 3",0,24*4,BLUE); g_CWindow.draw_text("Work thread 4",0,24*5,CYAN); g_CWindow.draw_text("Work thread 5",0,24*6,PURPLE); g_CWindow.draw_text("Work thread 6",0,24*7,YELLOW); g_CWindow.draw_text("Press 'v' to disable Thread Visualization mode",0,24*19,WHITE); } else { g_CWindow.draw_text("Press 'v' to enable Thread Visualization mode",0,24*19,WHITE); } g_CWindow.draw_text("Press 'p' to pause",0,24*17,WHITE); g_CWindow.draw_text("Controls: ARROWS to move and ENTER to fire",0,24*18,WHITE); backdrop(); //Draw our g_pCLoop backdrop } if((g_bRestart)&&(lost)) { //you suck at this game thread a(system,"start.exe"); SDL_Delay(100); //Give system enough time to execute new instance exit(0); } else g_bRestart = false; g_CWindow.draw(); //Update screen if(1000/60>(SDL_GetTicks()-u32Start)) //Always keep constant framerate (60fps) SDL_Delay(1000/60-(SDL_GetTicks()-u32Start)); } return 0; }
void Font::RenderToTexture(CSurface &texture, const string &str, dword height, dword style, D3DXCOLOR color, int maxWidth, bool fade) { xdk_d3d_video_t *d3d = (xdk_d3d_video_t*)driver.video_data; if (m_pFont == NULL) return; m_pFont->SetTextHeight(height); m_pFont->SetTextStyle(style); m_pFont->SetTextColor(color); dword dwMaxWidth = (maxWidth <= 0) ? 1000 : maxWidth; // get the exact width and height required to display the string dword dwRequiredWidth = GetRequiredWidth(str, height, style); dword dwRequiredHeight = GetRequiredHeight(str, height, style);; // calculate the texture width and height needed to display the font dword dwTextureWidth = dwRequiredWidth * 2; dword dwTextureHeight = dwRequiredHeight * 2; { // because the textures are swizzled we make sure // the dimensions are a power of two for(dword wmask = 1; dwTextureWidth &(dwTextureWidth - 1); wmask = (wmask << 1 ) + 1) dwTextureWidth = (dwTextureWidth + wmask) & ~wmask; for(dword hmask = 1; dwTextureHeight &(dwTextureHeight - 1); hmask = (hmask << 1) + 1) dwTextureHeight = ( dwTextureHeight + hmask ) & ~hmask; // also enforce a minimum pitch of 64 bytes dwTextureWidth = max(64 / XGBytesPerPixelFromFormat(D3DFMT_A8R8G8B8), dwTextureWidth); } // create an temporary image surface to render to D3DSurface *pTempSurface; d3d->d3d_render_device->CreateImageSurface(dwTextureWidth, dwTextureHeight, D3DFMT_LIN_A8R8G8B8, &pTempSurface); // clear the temporary surface { D3DLOCKED_RECT tmpLr; pTempSurface->LockRect(&tmpLr, NULL, 0); memset(tmpLr.pBits, 0, dwTextureWidth * dwTextureHeight * XGBytesPerPixelFromFormat(D3DFMT_A8R8G8B8)); pTempSurface->UnlockRect(); } // render the text to the temporary surface word *wcBuf = StringToWChar(str); m_pFont->TextOut(pTempSurface, wcBuf, -1, 0, 0); delete [] wcBuf; // create the texture that will be drawn to the screen texture.Destroy(); texture.Create(dwTextureWidth, dwTextureHeight); // copy from the temporary surface to the final texture { D3DLOCKED_RECT tmpLr; D3DLOCKED_RECT txtLr; pTempSurface->LockRect(&tmpLr, NULL, 0); texture.GetTexture()->LockRect(0, &txtLr, NULL, 0); if (fade) { // draw the last 35 pixels of the string fading out to max width or texture width dword dwMinFadeDistance = min(static_cast<dword>(dwTextureWidth * 0.35), 35); dword dwFadeStart = min(dwTextureWidth, dwMaxWidth - dwMinFadeDistance); dword dwFadeEnd = min(dwTextureWidth, dwMaxWidth); dword dwFadeDistance = dwFadeEnd - dwFadeStart; for (dword h = 0; h < dwTextureHeight; h++) { for (dword w = 0; w < dwFadeDistance; w++) { dword *pColor = reinterpret_cast<dword *>(tmpLr.pBits); dword offset = (h * dwTextureWidth) + (dwFadeStart + w); D3DXCOLOR color = D3DXCOLOR(pColor[offset]); color.a = color.a * (1.0f - static_cast<float>(w) / static_cast<float>(dwFadeDistance)); pColor[offset] = color; } } } // dont draw anything > than max width for (dword h = 0; h < dwTextureHeight; h++) { for (dword w = min(dwTextureWidth, dwMaxWidth); w < dwTextureWidth; w++) { dword *pColor = reinterpret_cast<dword *>(tmpLr.pBits); dword offset = (h * dwTextureWidth) + w; D3DXCOLOR color = D3DXCOLOR(pColor[offset]); color.a = 0.0; pColor[offset] = color; } } // copy and swizzle the linear surface to the swizzled texture XGSwizzleRect(tmpLr.pBits, tmpLr.Pitch, NULL, txtLr.pBits, dwTextureWidth, dwTextureHeight, NULL, 4); texture.GetTexture()->UnlockRect(0); pTempSurface->UnlockRect(); } pTempSurface->Release(); }
bool CMesh::Load(const PBASICCHAR pcFileName) { Destroy(); //加载网格模型 LPD3DXBUFFER pD3DXMtrlBuffer; HRESULT hr; hr = D3DXLoadMeshFromX( pcFileName, D3DXMESH_MANAGED, &DEVICE, NULL, &pD3DXMtrlBuffer, NULL, (DWORD*)&m_uNumSurfaces, &m_pMesh ); if( FAILED(hr) ) { DEBUG_WARNING(hr); return false; } DEBUG_NEW(m_pSurfaces, CSurface[m_uNumSurfaces]); //提取材质和纹理文件路径 D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer(); for( DWORD i = 0; i< m_uNumSurfaces; i ++ ) { // MatD3D属性里没有环境光的值设置,当它被加载时,需要设置它 d3dxMaterials[i].MatD3D.Ambient = d3dxMaterials[i].MatD3D.Diffuse; CSurface* pSurface = &m_pSurfaces[i]; pSurface->SetMaterial(d3dxMaterials[i].MatD3D); if( d3dxMaterials[i].pTextureFilename != NULL ) { //创建纹理 #ifdef _UNICODE BASICCHAR szFile[MAX_PATH]; RemovePathFromFileName(d3dxMaterials[i].pTextureFilename, szFile); BASICSTRING texFile; GetRealPath(pcFileName, texFile, TEXT("/"), szFile); pSurface->LoadTexture((PBASICCHAR)texFile.c_str(), 0); BASICSTRING normalMapFile; GetRealPath((PBASICCHAR)texFile.c_str(), normalMapFile, TEXT("."), TEXT("-normalmap.tga"), true); pSurface->LoadTexture((PBASICCHAR)normalMapFile.c_str(), 1) ; //return false; #else if( !pSurface->LoadTexture(d3dxMaterials[i].pTextureFilename, 0) ) return false; #endif } } DEBUG_RELEASE( pD3DXMtrlBuffer ); __GenerateDeclMesh(m_pMesh) && __GetBoundBox(m_pMesh, m_Rectangle); return true; }
bool NOX_MAP::AddObject(char objName[], int X, int Y, int callback) { /*RGBQUAD test; test.rgbBlue = 255; test.rgbRed = 255; Video.bmpfile.Set_Color(test); */ int ObjNum =0; GNHT * obj; for(obj = Thing.Thing.Object.Objects.Get(); obj && strcmp(obj->Name,objName); obj = Thing.Thing.Object.Objects.Get(), ObjNum++); Thing.Thing.Object.Objects.ClearGet(); OBJECT object; CSurface * surf = NULL; SURFACE tem; SURFACE * test = NULL; if( !obj ) return(false); IDX_DB::Entry * Entry = NULL; IDX_DB::SectionHeader * Section = NULL; long val = 0; // else if(obj->Stats.numNodes > 0 && obj->Stats.numNodes<2) // val = *obj->Stats.Get(0)->Images.Get(0); if(obj->Stats.numNodes) val = *obj->Stats.Get(0)->Images.Get(0); else if(obj->PrettyImage!=NULL) val = obj->PrettyImage; else if(obj->MenuIcon!=NULL) val = obj->MenuIcon; else return(false); if( val ) val++; else return(false); if( !val || val < 0 ) return(false); //test = Objects.ObjImages.Find(val); if( val && !(test = Objects.ObjImages.Find(val)) ) { Video.idx.GetAll((unsigned long)val,&Entry,&Section); //Video.Extract(&file,Section,Entry,"c://TESTMAP.bmp"); // Display.Display->CreateSurfaceFromBitmap(&surf,"C://TESTMAP.bmp"); // if( surf ) // surf->SetColorKey(RGB(0,0,0)); //remove("c://TESTMAP.bmp"); /////////////////////////////////////////////////////////////////////////////////////////////// if( Entry ) { fstream file; file.open(Video.bagpath,ios::in | ios::binary); NxImage *img = Video.Extract(&file,Section,Entry); if( img && img->height >0 && img->width >0) { Display.Display->CreateSurface(&surf,img->width,img->height); if( surf ) surf->SetColorKey(RGB(248,7,248)); Display.BltBitmapData(img->data, img->width, img->height, surf->GetDDrawSurface()); } tem.surface = surf; tem.Height = img->height; tem.Width = img->width; tem.Image_ID = val; tem.ImgType = Entry->Entry_Type; tem.OffsetX = Entry->OffsetX; tem.OffsetY = Entry->OffsetY; //tem.img.Load(img->width,img->height,img->offsetX,img->offsetY,img->data,(char*)&img->ID); img->Unload(); //LOAD THE NAME AS WELL NOW!!!!! Objects.ObjImages.Add(tem,val); test = &Objects.ObjImages.last->msg; file.close(); } /////////////////////////////////////////////////////////////////////////////////////////////// } object.imgID = val; object.objID = ObjNum; object.X = X; object.Y = Y; object.callbackID = callback; if(test) { object.Height = test->Height; object.Width = test->Width; } Objects.Objects.Add(object,object.callbackID); tem.surface = NULL; tem.name = NULL; surf = NULL; /*test.rgbBlue = 0; test.rgbRed = 0; Video.bmpfile.Set_Color(test); */ return(true); }
bool ESceneAIMapTool::GenerateMap(bool bFromSelectedOnly) { std::sort(m_ignored_materials.begin(),m_ignored_materials.end()); bool bRes = false; if (!GetSnapList()->empty()){ if (!RealUpdateSnapList()) return false; if (m_Nodes.empty()){ ELog.DlgMsg(mtError,"Append at least one node."); return false; } if (!m_Flags.is(flSlowCalculate)){ // evict resources ExecCommand (COMMAND_EVICT_OBJECTS); ExecCommand (COMMAND_EVICT_TEXTURES); // prepare collision model u32 avg_face_cnt = 0; u32 avg_vert_cnt = 0; u32 mesh_cnt = 0; Fbox snap_bb; { snap_bb.invalidate (); for (ObjectIt o_it=m_SnapObjects.begin(); o_it!=m_SnapObjects.end(); o_it++){ CSceneObject* S = dynamic_cast<CSceneObject*>(*o_it); VERIFY(S); avg_face_cnt += S->GetFaceCount(); avg_vert_cnt += S->GetVertexCount(); mesh_cnt += S->Meshes()->size(); Fbox bb; S->GetBox (bb); snap_bb.merge (bb); } } SPBItem* pb = UI->ProgressStart(mesh_cnt,"Prepare collision model..."); CDB::Collector* CL = ETOOLS::create_collector(); Fvector verts[3]; for (ObjectIt o_it=m_SnapObjects.begin(); o_it!=m_SnapObjects.end(); o_it++) { CSceneObject* S = dynamic_cast<CSceneObject*>(*o_it); VERIFY(S); CEditableObject* E = S->GetReference(); VERIFY(E); EditMeshVec& _meshes = E->Meshes(); for (EditMeshIt m_it=_meshes.begin(); m_it!=_meshes.end(); m_it++) { pb->Inc(AnsiString().sprintf("%s [%s]",S->Name,(*m_it)->Name().c_str()).c_str()); const SurfFaces& _sfaces = (*m_it)->GetSurfFaces(); for (SurfFaces::const_iterator sp_it=_sfaces.begin(); sp_it!=_sfaces.end(); sp_it++) { CSurface* surf = sp_it->first; // test passable //. SGameMtl* mtl = GMLib.GetMaterialByID(surf->_GameMtl()); //. if (mtl->Flags.is(SGameMtl::flPassable))continue; Shader_xrLC* c_sh = Device.ShaderXRLC.Get(surf->_ShaderXRLCName()); if (!c_sh->flags.bCollision) continue; // collect tris const IntVec& face_lst = sp_it->second; for (IntVec::const_iterator it=face_lst.begin(); it!=face_lst.end(); it++) { E->GetFaceWorld (S->_Transform(),*m_it,*it,verts); ETOOLS::collector_add_face_d(CL,verts[0],verts[1],verts[2], surf->_GameMtl() /* *it */); if (surf->m_Flags.is(CSurface::sf2Sided)) ETOOLS::collector_add_face_d(CL,verts[2],verts[1],verts[0], surf->_GameMtl() /* *it */); } } } } UI->ProgressEnd(pb); UI->SetStatus ("Building collision model..."); // create CFModel m_CFModel = ETOOLS::create_model_cl(CL); ETOOLS::destroy_collector(CL); } // building Scene->lock (); CTimer tm; tm.Start(); BuildNodes (bFromSelectedOnly); tm.GetElapsed_sec(); Scene->unlock (); //. Log("-test time: ", g_tm.GetElapsed_sec()); Log("-building time: ",tm.GetElapsed_sec()); //. Msg("-Rate: %3.2f Count: %d",(g_tm.GetElapsed_sec()/tm.GetElapsed_sec())*100.f,g_tm.count); // unload CFModel ETOOLS::destroy_model(m_CFModel); Scene->UndoSave (); bRes = true; UI->SetStatus (""); }else{ ELog.DlgMsg(mtError,"Fill snap list before generating slots!"); } return bRes; }
BOOL ESceneAIMapTool::CreateNode(Fvector& vAt, SAINode& N, bool bIC) { // *** Query and cache polygons for ray-casting Fvector PointUp; PointUp.set(vAt); PointUp.y += RCAST_Depth; SnapXZ (PointUp,m_Params.fPatchSize); Fvector PointDown; PointDown.set(vAt); PointDown.y -= RCAST_Depth; SnapXZ (PointDown,m_Params.fPatchSize); Fbox BB; BB.set (PointUp,PointUp); BB.grow(m_Params.fPatchSize/2); // box 1 Fbox B2; B2.set (PointDown,PointDown); B2.grow(m_Params.fPatchSize/2); // box 2 BB.merge (B2); if (m_CFModel) { /* for(u32 i=0; i<m_CFModel->get_tris_count(); ++i) { CDB::TRI* tri = (m_CFModel->get_tris()+i); if(tri->material!=0) Msg("non-default material"); } */ Scene->BoxQuery(PQ,BB,CDB::OPT_FULL_TEST,m_CFModel); }else Scene->BoxQuery(PQ,BB,CDB::OPT_FULL_TEST,GetSnapList()); DWORD dwCount = PQ.r_count(); if (dwCount==0){ // Log("chasm1"); return FALSE; // chasm? } // *** Transfer triangles and compute sector // R_ASSERT(dwCount<RCAST_MaxTris); static xr_vector<tri> tris; tris.reserve(RCAST_MaxTris); tris.clear(); for (DWORD i=0; i<dwCount; i++) { SPickQuery::SResult* R = PQ.r_begin()+i; if (R->e_obj&&R->e_mesh) { CSurface* surf = R->e_mesh->GetSurfaceByFaceID(R->tag); //. SGameMtl* mtl = GMLib.GetMaterialByID(surf->_GameMtl()); //. if (mtl->Flags.is(SGameMtl::flPassable))continue; Shader_xrLC* c_sh = Device.ShaderXRLC.Get(surf->_ShaderXRLCName()); if (!c_sh->flags.bCollision) continue; } /* if(m_CFModel) { u16 mtl_id = R->material; if(std::find(m_ignored_materials.begin(), m_ignored_materials.end(), mtl_id) != m_ignored_materials.end() ) { //. Msg("--ignore"); continue; } } */ tris.push_back (tri()); tri& D = tris.back(); Fvector* V = R->verts; D.v[0] = &V[0]; D.v[1] = &V[1]; D.v[2] = &V[2]; D.N.mknormal(*D.v[0],*D.v[1],*D.v[2]); if (D.N.y<=0) tris.pop_back (); } if (tris.size()==0){ // Log("chasm2"); return FALSE; // chasm? } static xr_vector<Fvector> points; points.reserve(RCAST_Total); points.clear(); static xr_vector<Fvector> normals; normals.reserve(RCAST_Total);normals.clear(); Fvector P,D; D.set(0,-1,0); float coeff = 0.5f*m_Params.fPatchSize/float(RCAST_Count); for (int x=-RCAST_Count; x<=RCAST_Count; x++) { P.x = vAt.x + coeff*float(x); for (int z=-RCAST_Count; z<=RCAST_Count; z++) { P.z = vAt.z + coeff*float(z); P.y = vAt.y + 10.f; float tri_min_range = flt_max; int tri_selected = -1; float range,u,v; for (i=0; i<DWORD(tris.size()); i++){ if (ETOOLS::TestRayTriA(P,D,tris[i].v,u,v,range,false)){ if (range<tri_min_range){ tri_min_range = range; tri_selected = i; } } } if (tri_selected>=0) { P.y -= tri_min_range; points.push_back(P); normals.push_back(tris[tri_selected].N); } } } if (points.size()<3) { // Msg ("Failed to create node at [%f,%f,%f].",vAt.x,vAt.y,vAt.z); return FALSE; } //. float rc_lim = bIC?0.015f:0.7f; if (float(points.size())/float(RCAST_Total) < rc_lim) { // Msg ("Partial chasm at [%f,%f,%f].",vAt.x,vAt.y,vAt.z); return FALSE; } // *** Calc normal Fvector vNorm; vNorm.set(0,0,0); for (DWORD n=0; n<normals.size(); n++) vNorm.add(normals[n]); vNorm.div(float(normals.size())); vNorm.normalize(); /* { // second algorithm (Magic) Fvector N,O; N.set(vNorm); O.set(points[0]); Mgc::OrthogonalPlaneFit( points.size(),(Mgc::Vector3*)points.begin(), *((Mgc::Vector3*)&O), *((Mgc::Vector3*)&N) ); if (N.y<0) N.invert(); N.normalize(); vNorm.lerp(vNorm,N,.3f); vNorm.normalize(); } */ // *** Align plane Fvector vOffs; vOffs.set(0,-1000,0); Fplane PL; PL.build(vOffs,vNorm); for (DWORD p=0; p<points.size(); p++) { float dist = PL.classify(points[p]); if (dist>0) { vOffs = points[p]; PL.build(vOffs,vNorm); } } // *** Create node and register it N.Plane.build (vOffs,vNorm); // build plane D.set (0,1,0); N.Plane.intersectRayPoint(PointDown,D,N.Pos); // "project" position // *** Validate results vNorm.set(0,1,0); if (vNorm.dotproduct(N.Plane.n)<_cos(deg2rad(60.f))) return FALSE; float y_old = vAt.y; float y_new = N.Pos.y; if (y_old>y_new) { // down if (y_old-y_new > m_Params.fCanDOWN ) return FALSE; } else { // up if (y_new-y_old > m_Params.fCanUP ) return FALSE; } // *** Validate plane { Fvector PLP; D.set(0,-1,0); int num_successed_rays = 0; for (int x=-RCAST_Count; x<=RCAST_Count; x++) { P.x = N.Pos.x + coeff*float(x); for (int z=-RCAST_Count; z<=RCAST_Count; z++) { P.z = N.Pos.z + coeff*float(z); P.y = N.Pos.y; N.Plane.intersectRayPoint(P,D,PLP); // "project" position P.y = PLP.y+RCAST_VALID*0.01f; float tri_min_range = flt_max; int tri_selected = -1; float range,u,v; for (i=0; i<tris.size(); i++){ if (ETOOLS::TestRayTriA(P,D,tris[i].v,u,v,range,false)){ if (range<tri_min_range){ tri_min_range = range; tri_selected = i; } } } if (tri_selected>=0){ if (tri_min_range<RCAST_VALID) num_successed_rays++; } } } float perc = float(num_successed_rays)/float(RCAST_Total); //. if (!bIC&&(perc < 0.5f)){ float perc_lim = bIC?0.015f:0.5f; if (perc < perc_lim){ // Msg ("Floating node."); return FALSE; } } // *** Mask check // ??? return TRUE; }
bool NOX_MAP::AddTile(char objName[], int X, int Y, int variation) { if( X < 0 || X > 255 || Y < 0 || Y > 255) return(false); int ObjNum=0; ROLF *tile = NULL; for(tile = Thing.Thing.Tile.Tiles.Get(); tile && strcmp(tile->Name,objName); tile = Thing.Thing.Tile.Tiles.Get(), ObjNum++); Thing.Thing.Tile.Tiles.ClearGet(); if( tile == NULL ) return false; IDX_DB::Entry * Entry = NULL; IDX_DB::SectionHeader * Section = NULL; CSurface * surf; SURFACE tem; SURFACE * test; unsigned int val = *tile->Images.Get(variation); tile->Images.ClearGet(); val++; test = Floor.TileImgs.Find(val); if( !test ) { surf = NULL; fstream file; file.open(Video.bagpath,ios::in | ios::binary); Video.idx.GetAll(val,&Entry,&Section); if( Entry ) { NxImage *img = Video.Extract(&file,Section,Entry); Display.Display->CreateSurface(&surf,img->width,img->height); if(surf) surf->SetColorKey(RGB(248,7,248)); Display.BltBitmapData(img->data,img->width,img->height,surf->GetDDrawSurface()); tem.surface = surf; tem.Height = img->height; tem.Width = img->width; tem.Image_ID = val; tem.ImgType = Entry->Entry_Type; tem.OffsetX = Entry->OffsetX; tem.OffsetY = Entry->OffsetY; img->Unload(); } //LOAD THE NAME AS WELL NOW!!!!! Floor.TileImgs.Add(tem,val); file.close(); Floor.tileMap[X][Y].pTile = &Floor.TileImgs.last->msg; } else { Floor.tileMap[X][Y].pTile = test; } Floor.tileMap[X][Y].Tile = ObjNum; Floor.tileMap[X][Y].tVari = variation; Floor.tileMap[X][Y].TileImg = val; Floor.TileImgs.ClearGet(); tem.surface = NULL; tem.name = NULL; surf = NULL; return(true); }
LPCSTR EDetail::GetTextureName() { VERIFY(m_pRefs); CSurface* surf = *m_pRefs->FirstSurface(); VERIFY(surf); return surf->_Texture(); }