2 Copyright (C) 2001-2006, William Joseph.
5 This file is part of GtkRadiant.
7 GtkRadiant is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 GtkRadiant is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GtkRadiant; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "referencecache.h"
23 #include "globaldefs.h"
25 #include "debugging/debugging.h"
27 #include "iscenegraph.h"
28 #include "iselection.h"
32 MapModules& ReferenceAPI_getMapModules();
36 ModelModules& ReferenceAPI_getModelModules();
38 #include "ifilesystem.h"
40 #include "ifiletypes.h"
41 #include "ireference.h"
43 #include "qerplugin.h"
47 #include "container/cache.h"
48 #include "container/hashfunc.h"
50 #include "stream/textfilestream.h"
51 #include "nullmodel.h"
53 #include "stream/stringstream.h"
55 #include "moduleobserver.h"
56 #include "moduleobservers.h"
58 #include "mainframe.h"
60 #include "filetypes.h"
62 extern bool g_writeMapComments;
64 bool References_Saved();
67 Map_SetModified( g_map, !References_Saved() );
71 EntityCreator* g_entityCreator = 0;
73 bool MapResource_loadFile( const MapFormat& format, scene::Node& root, const char* filename ){
74 globalOutputStream() << "Open file " << filename << " for read...";
75 TextFileInputStream file( filename );
76 if ( !file.failed() ) {
77 globalOutputStream() << "success\n";
78 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Loading Map" );
79 ASSERT_NOTNULL( g_entityCreator );
80 format.readGraph( root, file, *g_entityCreator );
85 globalErrorStream() << "failure\n";
90 NodeSmartReference MapResource_load( const MapFormat& format, const char* path, const char* name ){
91 NodeSmartReference root( NewMapRoot( name ) );
93 StringOutputStream fullpath( 256 );
94 fullpath << path << name;
96 if ( path_is_absolute( fullpath.c_str() ) ) {
97 MapResource_loadFile( format, root, fullpath.c_str() );
101 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
107 bool MapResource_saveFile( const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename ){
108 //ASSERT_MESSAGE(path_is_absolute(filename), "MapResource_saveFile: path is not absolute: " << makeQuoted(filename));
109 globalOutputStream() << "Open file " << filename << " for write...";
110 TextFileOutputStream file( filename );
111 if ( !file.failed() ) {
112 globalOutputStream() << "success\n";
113 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Saving Map" );
114 format.writeGraph( root, traverse, file, g_writeMapComments );
118 globalErrorStream() << "failure\n";
122 bool file_saveBackup( const char* path ){
123 if ( file_writeable( path ) ) {
124 StringOutputStream backup( 256 );
125 backup << StringRange( path, path_get_extension( path ) ) << "bak";
127 return file_move( path, backup.c_str() ); // rename current to backup
130 globalErrorStream() << "map path is not writeable: " << makeQuoted( path ) << "\n";
134 bool MapResource_save( const MapFormat& format, scene::Node& root, const char* path, const char* name ){
135 StringOutputStream fullpath( 256 );
136 fullpath << path << name;
138 if ( path_is_absolute( fullpath.c_str() ) ) {
139 /* We don't want a backup + rename operation if the .map file is
140 * a symlink. Otherwise we'll break the user's careful symlink setup.
141 * Just overwrite the original file. Assume the user has versioning. */
144 if ( lstat(fullpath.c_str(), &st) == 0 ) {
145 make_backup = true; // file exists
146 if ( (st.st_mode & S_IFMT) == S_IFLNK ) {
147 make_backup = false; // .. but it is a symlink
150 make_backup = false; // nothing to move
153 if ( !make_backup || file_saveBackup( fullpath.c_str() ) ) {
154 return MapResource_saveFile( format, root, Map_Traverse, fullpath.c_str() );
157 globalErrorStream() << "failed to save a backup map file: " << makeQuoted( fullpath.c_str() ) << "\n";
161 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
167 NodeSmartReference g_nullNode( NewNullNode() );
168 NodeSmartReference g_nullModel( g_nullNode );
171 class NullModelLoader : public ModelLoader
174 scene::Node& loadModel( ArchiveFile& file ){
181 NullModelLoader g_NullModelLoader;
185 /// \brief Returns the model loader for the model \p type or 0 if the model \p type has no loader module
186 ModelLoader* ModelLoader_forType( const char* type ){
187 const char* moduleName = findModuleName( &GlobalFiletypes(), ModelLoader::Name(), type );
188 if ( string_not_empty( moduleName ) ) {
189 ModelLoader* table = ReferenceAPI_getModelModules().findModule( moduleName );
195 globalErrorStream() << "ERROR: Model type incorrectly registered: \"" << moduleName << "\"\n";
196 return &g_NullModelLoader;
202 NodeSmartReference ModelResource_load( ModelLoader* loader, const char* name ){
203 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( name ), "Loading Model" );
205 NodeSmartReference model( g_nullModel );
208 ArchiveFile* file = GlobalFileSystem().openFile( name );
211 globalOutputStream() << "Loaded Model: \"" << name << "\"\n";
212 model = loader->loadModel( *file );
217 globalErrorStream() << "Model load failed: \"" << name << "\"\n";
221 model.get().m_isRoot = true;
227 inline hash_t path_hash( const char* path, hash_t previous = 0 ){
229 return string_hash_nocase( path, previous );
231 return string_hash( path, previous );
237 bool operator()( const CopiedString& path, const CopiedString& other ) const {
238 return path_equal( path.c_str(), other.c_str() );
244 typedef hash_t hash_type;
246 hash_type operator()( const CopiedString& path ) const {
247 return path_hash( path.c_str() );
251 typedef std::pair<CopiedString, CopiedString> ModelKey;
255 bool operator()( const ModelKey& key, const ModelKey& other ) const {
256 return path_equal( key.first.c_str(), other.first.c_str() ) && path_equal( key.second.c_str(), other.second.c_str() );
262 typedef hash_t hash_type;
264 hash_type operator()( const ModelKey& key ) const {
265 return hash_combine( path_hash( key.first.c_str() ), path_hash( key.second.c_str() ) );
269 typedef HashTable<ModelKey, NodeSmartReference, ModelKeyHash, ModelKeyEqual> ModelCache;
270 ModelCache g_modelCache;
271 bool g_modelCache_enabled = true;
273 ModelCache::iterator ModelCache_find( const char* path, const char* name ){
274 if ( g_modelCache_enabled ) {
275 return g_modelCache.find( ModelKey( path, name ) );
277 return g_modelCache.end();
280 ModelCache::iterator ModelCache_insert( const char* path, const char* name, scene::Node& node ){
281 if ( g_modelCache_enabled ) {
282 return g_modelCache.insert( ModelKey( path, name ), NodeSmartReference( node ) );
284 return g_modelCache.insert( ModelKey( "", "" ), g_nullModel );
287 void ModelCache_flush( const char* path, const char* name ){
288 ModelCache::iterator i = g_modelCache.find( ModelKey( path, name ) );
289 if ( i != g_modelCache.end() ) {
290 //ASSERT_MESSAGE((*i).value.getCount() == 0, "resource flushed while still in use: " << (*i).key.first.c_str() << (*i).key.second.c_str());
291 g_modelCache.erase( i );
295 void ModelCache_clear(){
296 g_modelCache_enabled = false;
297 g_modelCache.clear();
298 g_modelCache_enabled = true;
301 NodeSmartReference Model_load( ModelLoader* loader, const char* path, const char* name, const char* type ){
303 return ModelResource_load( loader, name );
307 const char* moduleName = findModuleName( &GlobalFiletypes(), MapFormat::Name(), type );
308 if ( string_not_empty( moduleName ) ) {
309 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
311 return MapResource_load( *format, path, name );
315 globalErrorStream() << "ERROR: Map type incorrectly registered: \"" << moduleName << "\"\n";
321 if ( string_not_empty( type ) ) {
322 globalErrorStream() << "Model type not supported: \"" << name << "\"\n";
331 bool g_realised = false;
333 // name may be absolute or relative
334 const char* rootPath( const char* name ){
335 return GlobalFileSystem().findRoot(
336 path_is_absolute( name )
338 : GlobalFileSystem().findFile( name )
343 struct ModelResource : public Resource
345 NodeSmartReference m_model;
346 const CopiedString m_originalName;
350 ModelLoader* m_loader;
351 ModuleObservers m_observers;
352 std::time_t m_modified;
353 std::size_t m_unrealised;
355 ModelResource( const CopiedString& name ) :
356 m_model( g_nullModel ),
357 m_originalName( name ),
358 m_type( path_get_extension( name.c_str() ) ),
362 m_loader = ModelLoader_forType( m_type.c_str() );
373 ASSERT_MESSAGE( !realised(), "ModelResource::~ModelResource: resource reference still realised: " << makeQuoted( m_name.c_str() ) );
377 ModelResource( const ModelResource& );
380 ModelResource& operator=( const ModelResource& );
382 void setModel( const NodeSmartReference& model ){
387 m_model = g_nullModel;
391 if ( g_modelCache_enabled ) {
393 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
394 if ( i == g_modelCache.end() ) {
395 i = ModelCache_insert(
398 Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() )
402 setModel( ( *i ).value );
406 setModel( Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() ) );
417 ASSERT_MESSAGE( realised(), "resource not realised" );
418 if ( m_model == g_nullModel ) {
422 return m_model != g_nullModel;
427 const char* moduleName = findModuleName( GetFileTypeRegistry(), MapFormat::Name(), m_type.c_str() );
428 if ( string_not_empty( moduleName ) ) {
429 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
430 if ( format != 0 && MapResource_save( *format, m_model.get(), m_path.c_str(), m_name.c_str() ) ) {
441 ModelCache_flush( m_path.c_str(), m_name.c_str() );
445 scene::Node* getNode(){
446 //if(m_model != g_nullModel)
448 return m_model.get_pointer();
453 void setNode( scene::Node* node ){
454 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
455 if ( i != g_modelCache.end() ) {
456 ( *i ).value = NodeSmartReference( *node );
458 setModel( NodeSmartReference( *node ) );
463 void attach( ModuleObserver& observer ){
467 m_observers.attach( observer );
470 void detach( ModuleObserver& observer ){
472 observer.unrealise();
474 m_observers.detach( observer );
478 return m_unrealised == 0;
482 ASSERT_MESSAGE( m_unrealised != 0, "ModelResource::realise: already realised" );
483 if ( --m_unrealised == 0 ) {
484 m_path = rootPath( m_originalName.c_str() );
485 m_name = path_make_relative( m_originalName.c_str(), m_path.c_str() );
487 //globalOutputStream() << "ModelResource::realise: " << m_path.c_str() << m_name.c_str() << "\n";
489 m_observers.realise();
494 if ( ++m_unrealised == 1 ) {
495 m_observers.unrealise();
497 //globalOutputStream() << "ModelResource::unrealise: " << m_path.c_str() << m_name.c_str() << "\n";
503 return Node_getMapFile( m_model ) != 0;
507 MapFile* map = Node_getMapFile( m_model );
509 map->setChangedCallback( makeCallbackF(MapChanged) );
513 std::time_t modified() const {
514 StringOutputStream fullpath( 256 );
515 fullpath << m_path.c_str() << m_name.c_str();
516 return file_modified( fullpath.c_str() );
520 m_modified = modified();
521 MapFile* map = Node_getMapFile( m_model );
527 bool mapSaved() const {
528 MapFile* map = Node_getMapFile( m_model );
530 return m_modified == modified() && map->saved();
535 bool isModified() const {
536 return ( ( !string_empty( m_path.c_str() ) // had or has an absolute path
537 && m_modified != modified() ) // AND disk timestamp changed
538 || !path_equal( rootPath( m_originalName.c_str() ), m_path.c_str() ) ); // OR absolute vfs-root changed
542 if ( isModified() ) {
550 class HashtableReferenceCache : public ReferenceCache, public ModuleObserver
552 typedef HashedCache<CopiedString, ModelResource, PathHash, PathEqual> ModelReferences;
553 ModelReferences m_references;
554 std::size_t m_unrealised;
556 class ModelReferencesSnapshot
558 ModelReferences& m_references;
559 typedef std::list<ModelReferences::iterator> Iterators;
560 Iterators m_iterators;
562 typedef Iterators::iterator iterator;
564 ModelReferencesSnapshot( ModelReferences& references ) : m_references( references ){
565 for ( ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i )
567 m_references.capture( i );
568 m_iterators.push_back( i );
572 ~ModelReferencesSnapshot(){
573 for ( Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i )
575 m_references.release( *i );
580 return m_iterators.begin();
584 return m_iterators.end();
590 typedef ModelReferences::iterator iterator;
592 HashtableReferenceCache() : m_unrealised( 1 ){
596 return m_references.begin();
600 return m_references.end();
604 m_references.clear();
607 Resource* capture( const char* path ){
608 //globalOutputStream() << "capture: \"" << path << "\"\n";
609 return m_references.capture( CopiedString( path ) ).get();
612 void release( const char* path ){
613 m_references.release( CopiedString( path ) );
614 //globalOutputStream() << "release: \"" << path << "\"\n";
617 void setEntityCreator( EntityCreator& entityCreator ){
618 g_entityCreator = &entityCreator;
621 bool realised() const {
622 return m_unrealised == 0;
626 ASSERT_MESSAGE( m_unrealised != 0, "HashtableReferenceCache::realise: already realised" );
627 if ( --m_unrealised == 0 ) {
631 ModelReferencesSnapshot snapshot( m_references );
632 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
634 ModelReferences::value_type& value = *( *i );
635 if ( value.value.count() != 1 ) {
636 value.value.get()->realise();
644 if ( ++m_unrealised == 1 ) {
648 ModelReferencesSnapshot snapshot( m_references );
649 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
651 ModelReferences::value_type& value = *( *i );
652 if ( value.value.count() != 1 ) {
653 value.value.get()->unrealise();
663 ModelReferencesSnapshot snapshot( m_references );
664 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
666 ModelResource* resource = ( *( *i ) ).value.get();
667 if ( !resource->isMap() ) {
676 HashtableReferenceCache g_referenceCache;
680 class ResourceVisitor
683 virtual void visit( const char* name, const char* path, const
687 void SaveReferences(){
688 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Saving Map" );
689 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
691 ( *i ).value->save();
696 bool References_Saved(){
697 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
699 scene::Node* node = ( *i ).value->getNode();
701 MapFile* map = Node_getMapFile( *node );
702 if ( map != 0 && !map->saved() ) {
710 void RefreshReferences(){
711 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Refreshing Models" );
712 g_referenceCache.refresh();
716 void FlushReferences(){
719 g_referenceCache.clear();
722 ReferenceCache& GetReferenceCache(){
723 return g_referenceCache;
727 #include "modulesystem/modulesmap.h"
728 #include "modulesystem/singletonmodule.h"
729 #include "modulesystem/moduleregistry.h"
731 class ReferenceDependencies :
732 public GlobalRadiantModuleRef,
733 public GlobalFileSystemModuleRef,
734 public GlobalFiletypesModuleRef
736 ModelModulesRef m_model_modules;
737 MapModulesRef m_map_modules;
739 ReferenceDependencies() :
740 m_model_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "modeltypes" ) ),
741 m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) )
745 ModelModules& getModelModules(){
746 return m_model_modules.get();
749 MapModules& getMapModules(){
750 return m_map_modules.get();
754 class ReferenceAPI : public TypeSystemRef
756 ReferenceCache* m_reference;
758 typedef ReferenceCache Type;
760 STRING_CONSTANT( Name, "*" );
763 g_nullModel = NewNullModel();
765 GlobalFileSystem().attach( g_referenceCache );
767 m_reference = &GetReferenceCache();
771 GlobalFileSystem().detach( g_referenceCache );
773 g_nullModel = g_nullNode;
776 ReferenceCache* getTable(){
781 typedef SingletonModule<ReferenceAPI, ReferenceDependencies> ReferenceModule;
782 typedef Static<ReferenceModule> StaticReferenceModule;
783 StaticRegisterModule staticRegisterReference( StaticReferenceModule::instance() );
785 ModelModules& ReferenceAPI_getModelModules(){
786 return StaticReferenceModule::instance().getDependencies().getModelModules();
789 MapModules& ReferenceAPI_getMapModules(){
790 return StaticReferenceModule::instance().getDependencies().getMapModules( );