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"
24 #include "debugging/debugging.h"
26 #include "iscenegraph.h"
27 #include "iselection.h"
30 MapModules& ReferenceAPI_getMapModules();
32 ModelModules& ReferenceAPI_getModelModules();
33 #include "ifilesystem.h"
35 #include "ifiletypes.h"
36 #include "ireference.h"
38 #include "qerplugin.h"
42 #include "container/cache.h"
43 #include "container/hashfunc.h"
45 #include "stream/textfilestream.h"
46 #include "nullmodel.h"
48 #include "stream/stringstream.h"
50 #include "moduleobserver.h"
51 #include "moduleobservers.h"
53 #include "mainframe.h"
55 #include "filetypes.h"
58 bool References_Saved();
61 Map_SetModified( g_map, !References_Saved() );
65 EntityCreator* g_entityCreator = 0;
67 bool MapResource_loadFile( const MapFormat& format, scene::Node& root, const char* filename ){
68 globalOutputStream() << "Open file " << filename << " for read...";
69 TextFileInputStream file( filename );
70 if ( !file.failed() ) {
71 globalOutputStream() << "success\n";
72 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Loading Map" );
73 ASSERT_NOTNULL( g_entityCreator );
74 format.readGraph( root, file, *g_entityCreator );
79 globalErrorStream() << "failure\n";
84 NodeSmartReference MapResource_load( const MapFormat& format, const char* path, const char* name ){
85 NodeSmartReference root( NewMapRoot( name ) );
87 StringOutputStream fullpath( 256 );
88 fullpath << path << name;
90 if ( path_is_absolute( fullpath.c_str() ) ) {
91 MapResource_loadFile( format, root, fullpath.c_str() );
95 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
101 bool MapResource_saveFile( const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename ){
102 //ASSERT_MESSAGE(path_is_absolute(filename), "MapResource_saveFile: path is not absolute: " << makeQuoted(filename));
103 globalOutputStream() << "Open file " << filename << " for write...";
104 TextFileOutputStream file( filename );
105 if ( !file.failed() ) {
106 globalOutputStream() << "success\n";
107 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Saving Map" );
108 format.writeGraph( root, traverse, file );
112 globalErrorStream() << "failure\n";
116 bool file_saveBackup( const char* path ){
117 if ( file_writeable( path ) ) {
118 StringOutputStream backup( 256 );
119 backup << StringRange( path, path_get_extension( path ) ) << "bak";
121 return ( !file_exists( backup.c_str() ) || file_remove( backup.c_str() ) ) // remove backup
122 && file_move( path, backup.c_str() ); // rename current to backup
125 globalErrorStream() << "map path is not writeable: " << makeQuoted( path ) << "\n";
129 bool MapResource_save( const MapFormat& format, scene::Node& root, const char* path, const char* name ){
130 StringOutputStream fullpath( 256 );
131 fullpath << path << name;
133 if ( path_is_absolute( fullpath.c_str() ) ) {
134 if ( !file_exists( fullpath.c_str() ) || file_saveBackup( fullpath.c_str() ) ) {
135 return MapResource_saveFile( format, root, Map_Traverse, fullpath.c_str() );
138 globalErrorStream() << "failed to save a backup map file: " << makeQuoted( fullpath.c_str() ) << "\n";
142 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
148 NodeSmartReference g_nullNode( NewNullNode() );
149 NodeSmartReference g_nullModel( g_nullNode );
152 class NullModelLoader : public ModelLoader
155 scene::Node& loadModel( ArchiveFile& file ){
162 NullModelLoader g_NullModelLoader;
166 /// \brief Returns the model loader for the model \p type or 0 if the model \p type has no loader module
167 ModelLoader* ModelLoader_forType( const char* type ){
168 const char* moduleName = findModuleName( &GlobalFiletypes(), ModelLoader::Name(), type );
169 if ( string_not_empty( moduleName ) ) {
170 ModelLoader* table = ReferenceAPI_getModelModules().findModule( moduleName );
176 globalErrorStream() << "ERROR: Model type incorrectly registered: \"" << moduleName << "\"\n";
177 return &g_NullModelLoader;
183 NodeSmartReference ModelResource_load( ModelLoader* loader, const char* name ){
184 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( name ), "Loading Model" );
186 NodeSmartReference model( g_nullModel );
189 ArchiveFile* file = GlobalFileSystem().openFile( name );
192 globalOutputStream() << "Loaded Model: \"" << name << "\"\n";
193 model = loader->loadModel( *file );
198 globalErrorStream() << "Model load failed: \"" << name << "\"\n";
202 model.get().m_isRoot = true;
208 inline hash_t path_hash( const char* path, hash_t previous = 0 ){
210 return string_hash_nocase( path, previous );
212 return string_hash( path, previous );
218 bool operator()( const CopiedString& path, const CopiedString& other ) const {
219 return path_equal( path.c_str(), other.c_str() );
225 typedef hash_t hash_type;
226 hash_type operator()( const CopiedString& path ) const {
227 return path_hash( path.c_str() );
231 typedef std::pair<CopiedString, CopiedString> ModelKey;
235 bool operator()( const ModelKey& key, const ModelKey& other ) const {
236 return path_equal( key.first.c_str(), other.first.c_str() ) && path_equal( key.second.c_str(), other.second.c_str() );
242 typedef hash_t hash_type;
243 hash_type operator()( const ModelKey& key ) const {
244 return hash_combine( path_hash( key.first.c_str() ), path_hash( key.second.c_str() ) );
248 typedef HashTable<ModelKey, NodeSmartReference, ModelKeyHash, ModelKeyEqual> ModelCache;
249 ModelCache g_modelCache;
250 bool g_modelCache_enabled = true;
252 ModelCache::iterator ModelCache_find( const char* path, const char* name ){
253 if ( g_modelCache_enabled ) {
254 return g_modelCache.find( ModelKey( path, name ) );
256 return g_modelCache.end();
259 ModelCache::iterator ModelCache_insert( const char* path, const char* name, scene::Node& node ){
260 if ( g_modelCache_enabled ) {
261 return g_modelCache.insert( ModelKey( path, name ), NodeSmartReference( node ) );
263 return g_modelCache.insert( ModelKey( "", "" ), g_nullModel );
266 void ModelCache_flush( const char* path, const char* name ){
267 ModelCache::iterator i = g_modelCache.find( ModelKey( path, name ) );
268 if ( i != g_modelCache.end() ) {
269 //ASSERT_MESSAGE((*i).value.getCount() == 0, "resource flushed while still in use: " << (*i).key.first.c_str() << (*i).key.second.c_str());
270 g_modelCache.erase( i );
274 void ModelCache_clear(){
275 g_modelCache_enabled = false;
276 g_modelCache.clear();
277 g_modelCache_enabled = true;
280 NodeSmartReference Model_load( ModelLoader* loader, const char* path, const char* name, const char* type ){
282 return ModelResource_load( loader, name );
286 const char* moduleName = findModuleName( &GlobalFiletypes(), MapFormat::Name(), type );
287 if ( string_not_empty( moduleName ) ) {
288 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
290 return MapResource_load( *format, path, name );
294 globalErrorStream() << "ERROR: Map type incorrectly registered: \"" << moduleName << "\"\n";
300 if ( string_not_empty( type ) ) {
301 globalErrorStream() << "Model type not supported: \"" << name << "\"\n";
310 bool g_realised = false;
312 // name may be absolute or relative
313 const char* rootPath( const char* name ){
314 return GlobalFileSystem().findRoot(
315 path_is_absolute( name )
317 : GlobalFileSystem().findFile( name )
322 struct ModelResource : public Resource
324 NodeSmartReference m_model;
325 const CopiedString m_originalName;
329 ModelLoader* m_loader;
330 ModuleObservers m_observers;
331 std::time_t m_modified;
332 std::size_t m_unrealised;
334 ModelResource( const CopiedString& name ) :
335 m_model( g_nullModel ),
336 m_originalName( name ),
337 m_type( path_get_extension( name.c_str() ) ),
341 m_loader = ModelLoader_forType( m_type.c_str() );
351 ASSERT_MESSAGE( !realised(), "ModelResource::~ModelResource: resource reference still realised: " << makeQuoted( m_name.c_str() ) );
354 ModelResource( const ModelResource& );
356 ModelResource& operator=( const ModelResource& );
358 void setModel( const NodeSmartReference& model ){
362 m_model = g_nullModel;
366 if ( g_modelCache_enabled ) {
368 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
369 if ( i == g_modelCache.end() ) {
370 i = ModelCache_insert(
373 Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() )
377 setModel( ( *i ).value );
381 setModel( Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() ) );
392 ASSERT_MESSAGE( realised(), "resource not realised" );
393 if ( m_model == g_nullModel ) {
397 return m_model != g_nullModel;
401 const char* moduleName = findModuleName( GetFileTypeRegistry(), MapFormat::Name(), m_type.c_str() );
402 if ( string_not_empty( moduleName ) ) {
403 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
404 if ( format != 0 && MapResource_save( *format, m_model.get(), m_path.c_str(), m_name.c_str() ) ) {
414 ModelCache_flush( m_path.c_str(), m_name.c_str() );
417 scene::Node* getNode(){
418 //if(m_model != g_nullModel)
420 return m_model.get_pointer();
424 void setNode( scene::Node* node ){
425 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
426 if ( i != g_modelCache.end() ) {
427 ( *i ).value = NodeSmartReference( *node );
429 setModel( NodeSmartReference( *node ) );
433 void attach( ModuleObserver& observer ){
437 m_observers.attach( observer );
439 void detach( ModuleObserver& observer ){
441 observer.unrealise();
443 m_observers.detach( observer );
446 return m_unrealised == 0;
449 ASSERT_MESSAGE( m_unrealised != 0, "ModelResource::realise: already realised" );
450 if ( --m_unrealised == 0 ) {
451 m_path = rootPath( m_originalName.c_str() );
452 m_name = path_make_relative( m_originalName.c_str(), m_path.c_str() );
454 //globalOutputStream() << "ModelResource::realise: " << m_path.c_str() << m_name.c_str() << "\n";
456 m_observers.realise();
460 if ( ++m_unrealised == 1 ) {
461 m_observers.unrealise();
463 //globalOutputStream() << "ModelResource::unrealise: " << m_path.c_str() << m_name.c_str() << "\n";
468 return Node_getMapFile( m_model ) != 0;
471 MapFile* map = Node_getMapFile( m_model );
473 map->setChangedCallback( FreeCaller<MapChanged>() );
476 std::time_t modified() const {
477 StringOutputStream fullpath( 256 );
478 fullpath << m_path.c_str() << m_name.c_str();
479 return file_modified( fullpath.c_str() );
482 m_modified = modified();
483 MapFile* map = Node_getMapFile( m_model );
488 bool mapSaved() const {
489 MapFile* map = Node_getMapFile( m_model );
491 return m_modified == modified() && map->saved();
495 bool isModified() const {
496 return ( ( !string_empty( m_path.c_str() ) // had or has an absolute path
497 && m_modified != modified() ) // AND disk timestamp changed
498 || !path_equal( rootPath( m_originalName.c_str() ), m_path.c_str() ) ); // OR absolute vfs-root changed
501 if ( isModified() ) {
509 class HashtableReferenceCache : public ReferenceCache, public ModuleObserver
511 typedef HashedCache<CopiedString, ModelResource, PathHash, PathEqual> ModelReferences;
512 ModelReferences m_references;
513 std::size_t m_unrealised;
515 class ModelReferencesSnapshot
517 ModelReferences& m_references;
518 typedef std::list<ModelReferences::iterator> Iterators;
519 Iterators m_iterators;
521 typedef Iterators::iterator iterator;
522 ModelReferencesSnapshot( ModelReferences& references ) : m_references( references ){
523 for ( ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i )
525 m_references.capture( i );
526 m_iterators.push_back( i );
529 ~ModelReferencesSnapshot(){
530 for ( Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i )
532 m_references.release( *i );
536 return m_iterators.begin();
539 return m_iterators.end();
545 typedef ModelReferences::iterator iterator;
547 HashtableReferenceCache() : m_unrealised( 1 ){
551 return m_references.begin();
554 return m_references.end();
558 m_references.clear();
561 Resource* capture( const char* path ){
562 //globalOutputStream() << "capture: \"" << path << "\"\n";
563 return m_references.capture( CopiedString( path ) ).get();
565 void release( const char* path ){
566 m_references.release( CopiedString( path ) );
567 //globalOutputStream() << "release: \"" << path << "\"\n";
570 void setEntityCreator( EntityCreator& entityCreator ){
571 g_entityCreator = &entityCreator;
574 bool realised() const {
575 return m_unrealised == 0;
578 ASSERT_MESSAGE( m_unrealised != 0, "HashtableReferenceCache::realise: already realised" );
579 if ( --m_unrealised == 0 ) {
583 ModelReferencesSnapshot snapshot( m_references );
584 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
586 ModelReferences::value_type& value = *( *i );
587 if ( value.value.count() != 1 ) {
588 value.value.get()->realise();
595 if ( ++m_unrealised == 1 ) {
599 ModelReferencesSnapshot snapshot( m_references );
600 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
602 ModelReferences::value_type& value = *( *i );
603 if ( value.value.count() != 1 ) {
604 value.value.get()->unrealise();
613 ModelReferencesSnapshot snapshot( m_references );
614 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
616 ModelResource* resource = ( *( *i ) ).value.get();
617 if ( !resource->isMap() ) {
626 HashtableReferenceCache g_referenceCache;
630 class ResourceVisitor
633 virtual void visit( const char* name, const char* path, const
637 void SaveReferences(){
638 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Saving Map" );
639 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
641 ( *i ).value->save();
646 bool References_Saved(){
647 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
649 scene::Node* node = ( *i ).value->getNode();
651 MapFile* map = Node_getMapFile( *node );
652 if ( map != 0 && !map->saved() ) {
660 void RefreshReferences(){
661 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Refreshing Models" );
662 g_referenceCache.refresh();
666 void FlushReferences(){
669 g_referenceCache.clear();
672 ReferenceCache& GetReferenceCache(){
673 return g_referenceCache;
677 #include "modulesystem/modulesmap.h"
678 #include "modulesystem/singletonmodule.h"
679 #include "modulesystem/moduleregistry.h"
681 class ReferenceDependencies :
682 public GlobalRadiantModuleRef,
683 public GlobalFileSystemModuleRef,
684 public GlobalFiletypesModuleRef
686 ModelModulesRef m_model_modules;
687 MapModulesRef m_map_modules;
689 ReferenceDependencies() :
690 m_model_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "modeltypes" ) ),
691 m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) )
694 ModelModules& getModelModules(){
695 return m_model_modules.get();
697 MapModules& getMapModules(){
698 return m_map_modules.get();
702 class ReferenceAPI : public TypeSystemRef
704 ReferenceCache* m_reference;
706 typedef ReferenceCache Type;
707 STRING_CONSTANT( Name, "*" );
710 g_nullModel = NewNullModel();
712 GlobalFileSystem().attach( g_referenceCache );
714 m_reference = &GetReferenceCache();
717 GlobalFileSystem().detach( g_referenceCache );
719 g_nullModel = g_nullNode;
721 ReferenceCache* getTable(){
726 typedef SingletonModule<ReferenceAPI, ReferenceDependencies> ReferenceModule;
727 typedef Static<ReferenceModule> StaticReferenceModule;
728 StaticRegisterModule staticRegisterReference( StaticReferenceModule::instance() );
730 ModelModules& ReferenceAPI_getModelModules(){
731 return StaticReferenceModule::instance().getDependencies().getModelModules();
733 MapModules& ReferenceAPI_getMapModules(){
734 return StaticReferenceModule::instance().getDependencies().getMapModules( );