]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/entity.cpp
redo a windows fix from 20dbf5c that was mistakenly lost
[xonotic/netradiant.git] / radiant / entity.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
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.
11
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.
16
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
20  */
21
22 #include "entity.h"
23
24 #include "ientity.h"
25 #include "iselection.h"
26 #include "imodel.h"
27 #include "ifilesystem.h"
28 #include "iundo.h"
29 #include "editable.h"
30
31 #include "eclasslib.h"
32 #include "scenelib.h"
33 #include "os/path.h"
34 #include "os/file.h"
35 #include "stream/stringstream.h"
36 #include "stringio.h"
37
38 #include "gtkutil/filechooser.h"
39 #include "gtkmisc.h"
40 #include "select.h"
41 #include "map.h"
42 #include "preferences.h"
43 #include "preferencesystem.h"
44 #include "stringio.h"
45 #include "gtkdlgs.h"
46 #include "mainframe.h"
47 #include "qe3.h"
48 #include "commands.h"
49
50 #include "uilib/uilib.h"
51
52 struct entity_globals_t
53 {
54         Vector3 color_entity;
55
56         entity_globals_t() :
57                 color_entity( 0.0f, 0.0f, 0.0f ){
58         }
59 };
60
61 entity_globals_t g_entity_globals;
62
63 class EntitySetKeyValueSelected : public scene::Graph::Walker
64 {
65 const char* m_key;
66 const char* m_value;
67 public:
68 EntitySetKeyValueSelected( const char* key, const char* value )
69         : m_key( key ), m_value( value ){
70 }
71
72 bool pre( const scene::Path& path, scene::Instance& instance ) const {
73         return true;
74 }
75
76 void post( const scene::Path& path, scene::Instance& instance ) const {
77         Entity* entity = Node_getEntity( path.top() );
78         if ( entity != 0
79                  && ( instance.childSelected() || Instance_getSelectable( instance )->isSelected() ) ) {
80                 entity->setKeyValue( m_key, m_value );
81         }
82 }
83 };
84
85 class EntitySetClassnameSelected : public scene::Graph::Walker
86 {
87 const char* m_classname;
88 public:
89 EntitySetClassnameSelected( const char* classname )
90         : m_classname( classname ){
91 }
92 bool pre( const scene::Path& path, scene::Instance& instance ) const {
93         return true;
94 }
95 void post( const scene::Path& path, scene::Instance& instance ) const {
96         Entity* entity = Node_getEntity( path.top() );
97         if ( entity != 0
98                  && ( instance.childSelected() || Instance_getSelectable( instance )->isSelected() ) ) {
99                 NodeSmartReference node( GlobalEntityCreator().createEntity( GlobalEntityClassManager().findOrInsert( m_classname, node_is_group( path.top() ) ) ) );
100
101                 EntityCopyingVisitor visitor( *Node_getEntity( node ) );
102
103                 entity->forEachKeyValue( visitor );
104
105                 NodeSmartReference child( path.top().get() );
106                 NodeSmartReference parent( path.parent().get() );
107                 Node_getTraversable( parent )->erase( child );
108                 if ( Node_getTraversable( child ) != 0
109                          && Node_getTraversable( node ) != 0
110                          && node_is_group( node ) ) {
111                         parentBrushes( child, node );
112                 }
113                 Node_getTraversable( parent )->insert( node );
114         }
115 }
116 };
117
118 void Scene_EntitySetKeyValue_Selected( const char* key, const char* value ){
119         GlobalSceneGraph().traverse( EntitySetKeyValueSelected( key, value ) );
120 }
121
122 void Scene_EntitySetClassname_Selected( const char* classname ){
123         GlobalSceneGraph().traverse( EntitySetClassnameSelected( classname ) );
124 }
125
126
127 void Entity_ungroupSelected(){
128         if ( GlobalSelectionSystem().countSelected() < 1 ) {
129                 return;
130         }
131
132         UndoableCommand undo( "ungroupSelectedEntities" );
133
134         scene::Path world_path( makeReference( GlobalSceneGraph().root() ) );
135         world_path.push( makeReference( Map_FindOrInsertWorldspawn( g_map ) ) );
136
137         scene::Instance &instance = GlobalSelectionSystem().ultimateSelected();
138         scene::Path path = instance.path();
139
140         if ( !Node_isEntity( path.top() ) ) {
141                 path.pop();
142         }
143
144         if ( Node_getEntity( path.top() ) != 0
145                  && node_is_group( path.top() ) ) {
146                 if ( world_path.top().get_pointer() != path.top().get_pointer() ) {
147                         parentBrushes( path.top(), world_path.top() );
148                         Path_deleteTop( path );
149                 }
150         }
151 }
152
153
154 class EntityFindSelected : public scene::Graph::Walker
155 {
156 public:
157 mutable const scene::Path *groupPath;
158 mutable scene::Instance *groupInstance;
159
160 EntityFindSelected() : groupPath( 0 ), groupInstance( 0 ){
161 }
162
163 bool pre( const scene::Path& path, scene::Instance& instance ) const {
164         return true;
165 }
166
167 void post( const scene::Path& path, scene::Instance& instance ) const {
168         Entity* entity = Node_getEntity( path.top() );
169         if ( entity != 0
170                  && Instance_getSelectable( instance )->isSelected()
171                  && node_is_group( path.top() )
172                  && !groupPath ) {
173                 groupPath = &path;
174                 groupInstance = &instance;
175         }
176 }
177 };
178
179 class EntityGroupSelected : public scene::Graph::Walker
180 {
181 NodeSmartReference group, worldspawn;
182 //typedef std::pair<NodeSmartReference, NodeSmartReference> DeletionPair;
183 //Stack<DeletionPair> deleteme;
184 public:
185 EntityGroupSelected( const scene::Path &p ) : group( p.top().get() ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
186 }
187
188 bool pre( const scene::Path& path, scene::Instance& instance ) const {
189         return true;
190 }
191
192 void post( const scene::Path& path, scene::Instance& instance ) const {
193         Selectable *selectable = Instance_getSelectable( instance );
194         if ( selectable && selectable->isSelected() ) {
195                 Entity* entity = Node_getEntity( path.top() );
196                 if ( entity == 0 && Node_isPrimitive( path.top() ) ) {
197                         NodeSmartReference child( path.top().get() );
198                         NodeSmartReference parent( path.parent().get() );
199
200                         if ( path.size() >= 3 && parent != worldspawn ) {
201                                 NodeSmartReference parentparent( path[path.size() - 3].get() );
202
203                                 Node_getTraversable( parent )->erase( child );
204                                 Node_getTraversable( group )->insert( child );
205
206                                 if ( Node_getTraversable( parent )->empty() ) {
207                                         //deleteme.push(DeletionPair(parentparent, parent));
208                                         Node_getTraversable( parentparent )->erase( parent );
209                                 }
210                         }
211                         else
212                         {
213                                 Node_getTraversable( parent )->erase( child );
214                                 Node_getTraversable( group )->insert( child );
215                         }
216                 }
217         }
218 }
219 };
220
221 void Entity_groupSelected(){
222         if ( GlobalSelectionSystem().countSelected() < 1 ) {
223                 return;
224         }
225
226         UndoableCommand undo( "groupSelectedEntities" );
227
228         scene::Path world_path( makeReference( GlobalSceneGraph().root() ) );
229         world_path.push( makeReference( Map_FindOrInsertWorldspawn( g_map ) ) );
230
231         EntityFindSelected fse;
232         GlobalSceneGraph().traverse( fse );
233         if ( fse.groupPath ) {
234                 GlobalSceneGraph().traverse( EntityGroupSelected( *fse.groupPath ) );
235         }
236         else
237         {
238                 GlobalSceneGraph().traverse( EntityGroupSelected( world_path ) );
239         }
240 }
241
242
243 void Entity_connectSelected(){
244         if ( GlobalSelectionSystem().countSelected() == 2 ) {
245                 GlobalEntityCreator().connectEntities(
246                         GlobalSelectionSystem().penultimateSelected().path(),
247                         GlobalSelectionSystem().ultimateSelected().path(),
248                         0
249                         );
250         }
251         else
252         {
253                 globalErrorStream() << "entityConnectSelected: exactly two instances must be selected\n";
254         }
255 }
256
257 void Entity_killconnectSelected(){
258         if ( GlobalSelectionSystem().countSelected() == 2 ) {
259                 GlobalEntityCreator().connectEntities(
260                         GlobalSelectionSystem().penultimateSelected().path(),
261                         GlobalSelectionSystem().ultimateSelected().path(),
262                         1
263                         );
264         }
265         else
266         {
267                 globalErrorStream() << "entityKillConnectSelected: exactly two instances must be selected\n";
268         }
269 }
270
271 AABB Doom3Light_getBounds( const AABB& workzone ){
272         AABB aabb( workzone );
273
274         Vector3 defaultRadius( 300, 300, 300 );
275         if ( !string_parse_vector3( EntityClass_valueForKey( *GlobalEntityClassManager().findOrInsert( "light", false ), "light_radius" ), defaultRadius ) ) {
276                 globalErrorStream() << "Doom3Light_getBounds: failed to parse default light radius\n";
277         }
278
279         if ( aabb.extents[0] == 0 ) {
280                 aabb.extents[0] = defaultRadius[0];
281         }
282         if ( aabb.extents[1] == 0 ) {
283                 aabb.extents[1] = defaultRadius[1];
284         }
285         if ( aabb.extents[2] == 0 ) {
286                 aabb.extents[2] = defaultRadius[2];
287         }
288
289         if ( aabb_valid( aabb ) ) {
290                 return aabb;
291         }
292         return AABB( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
293 }
294
295 int g_iLastLightIntensity;
296
297 void Entity_createFromSelection( const char* name, const Vector3& origin ){
298 #if 0
299         if ( string_equal_nocase( name, "worldspawn" ) ) {
300                 ui::alert( MainFrame_getWindow( ), "Can't create an entity with worldspawn.", "info" );
301                 return;
302         }
303 #endif
304
305         EntityClass* entityClass = GlobalEntityClassManager().findOrInsert( name, true );
306
307         bool isModel = ( string_compare_nocase_n( name, "misc_", 5 ) == 0 && string_equal_nocase( name + string_length( name ) - 5, "model" ) ) // misc_*model (also misc_model)
308                                    || string_equal_nocase( name, "model_static" )
309                                    || ( GlobalSelectionSystem().countSelected() == 0 && string_equal_nocase( name, "func_static" ) );
310
311         bool brushesSelected = Scene_countSelectedBrushes( GlobalSceneGraph() ) != 0;
312
313         if ( !( entityClass->fixedsize || isModel ) && !brushesSelected ) {
314                 globalErrorStream() << "failed to create a group entity - no brushes are selected\n";
315                 return;
316         }
317
318         AABB workzone( aabb_for_minmax( Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max ) );
319
320
321         NodeSmartReference node( GlobalEntityCreator().createEntity( entityClass ) );
322
323         Node_getTraversable( GlobalSceneGraph().root() )->insert( node );
324
325         scene::Path entitypath( makeReference( GlobalSceneGraph().root() ) );
326         entitypath.push( makeReference( node.get() ) );
327         scene::Instance& instance = findInstance( entitypath );
328
329         if ( entityClass->fixedsize || ( isModel && !brushesSelected ) ) {
330                 Select_Delete();
331
332                 Transformable* transform = Instance_getTransformable( instance );
333                 if ( transform != 0 ) {
334                         transform->setType( TRANSFORM_PRIMITIVE );
335                         transform->setTranslation( origin );
336                         transform->freezeTransform();
337                 }
338
339                 GlobalSelectionSystem().setSelectedAll( false );
340
341                 Instance_setSelected( instance, true );
342         }
343         else
344         {
345                 if ( g_pGameDescription->mGameType == "doom3" ) {
346                         Node_getEntity( node )->setKeyValue( "model", Node_getEntity( node )->getKeyValue( "name" ) );
347                 }
348
349                 Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), node );
350                 Scene_forEachChildSelectable( SelectableSetSelected( true ), instance.path() );
351         }
352
353         // tweaking: when right clic dropping a light entity, ask for light value in a custom dialog box
354         // see SF bug 105383
355
356         if ( g_pGameDescription->mGameType == "hl" ) {
357                 // FIXME - Hydra: really we need a combined light AND color dialog for halflife.
358                 if ( string_equal_nocase( name, "light" )
359                          || string_equal_nocase( name, "light_environment" )
360                          || string_equal_nocase( name, "light_spot" ) ) {
361                         int intensity = g_iLastLightIntensity;
362
363                         if ( DoLightIntensityDlg( &intensity ) == eIDOK ) {
364                                 g_iLastLightIntensity = intensity;
365                                 char buf[30];
366                                 sprintf( buf, "255 255 255 %d", intensity );
367                                 Node_getEntity( node )->setKeyValue( "_light", buf );
368                         }
369                 }
370         }
371         else if ( string_equal_nocase( name, "light" ) ) {
372                 if ( g_pGameDescription->mGameType != "doom3" ) {
373                         int intensity = g_iLastLightIntensity;
374
375                         if ( DoLightIntensityDlg( &intensity ) == eIDOK ) {
376                                 g_iLastLightIntensity = intensity;
377                                 char buf[10];
378                                 sprintf( buf, "%d", intensity );
379                                 Node_getEntity( node )->setKeyValue( "light", buf );
380                         }
381                 }
382                 else if ( brushesSelected ) { // use workzone to set light position/size for doom3 lights, if there are brushes selected
383                         AABB bounds( Doom3Light_getBounds( workzone ) );
384                         StringOutputStream key( 64 );
385                         key << bounds.origin[0] << " " << bounds.origin[1] << " " << bounds.origin[2];
386                         Node_getEntity( node )->setKeyValue( "origin", key.c_str() );
387                         key.clear();
388                         key << bounds.extents[0] << " " << bounds.extents[1] << " " << bounds.extents[2];
389                         Node_getEntity( node )->setKeyValue( "light_radius", key.c_str() );
390                 }
391         }
392
393         if ( isModel ) {
394                 const char* model = misc_model_dialog(MainFrame_getWindow());
395                 if ( model != 0 ) {
396                         Node_getEntity( node )->setKeyValue( "model", model );
397                 }
398         }
399 }
400
401 #if 0
402 bool DoNormalisedColor( Vector3& color ){
403         if ( !color_dialog( MainFrame_getWindow( ), color ) ) {
404                 return false;
405         }
406         /*
407         ** scale colors so that at least one component is at 1.0F
408         */
409
410         float largest = 0.0F;
411
412         if ( color[0] > largest ) {
413                 largest = color[0];
414         }
415         if ( color[1] > largest ) {
416                 largest = color[1];
417         }
418         if ( color[2] > largest ) {
419                 largest = color[2];
420         }
421
422         if ( largest == 0.0F ) {
423                 color[0] = 1.0F;
424                 color[1] = 1.0F;
425                 color[2] = 1.0F;
426         }
427         else
428         {
429                 float scaler = 1.0F / largest;
430
431                 color[0] *= scaler;
432                 color[1] *= scaler;
433                 color[2] *= scaler;
434         }
435
436         return true;
437 }
438 #endif
439
440 void NormalizeColor( Vector3& color ){
441         // scale colors so that at least one component is at 1.0F
442
443         float largest = 0.0F;
444
445         if ( color[0] > largest ) {
446                 largest = color[0];
447         }
448         if ( color[1] > largest ) {
449                 largest = color[1];
450         }
451         if ( color[2] > largest ) {
452                 largest = color[2];
453         }
454
455         if ( largest == 0.0F ) {
456                 color[0] = 1.0F;
457                 color[1] = 1.0F;
458                 color[2] = 1.0F;
459         }
460         else
461         {
462                 float scaler = 1.0F / largest;
463
464                 color[0] *= scaler;
465                 color[1] *= scaler;
466                 color[2] *= scaler;
467         }
468 }
469
470 void Entity_normalizeColor(){
471         if ( GlobalSelectionSystem().countSelected() != 0 ) {
472                 const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path();
473                 Entity* entity = Node_getEntity( path.top() );
474
475                 if ( entity != 0 ) {
476                         const char* strColor = entity->getKeyValue( "_color" );
477                         if ( !string_empty( strColor ) ) {
478                                 Vector3 rgb;
479                                 if ( string_parse_vector3( strColor, rgb ) ) {
480                                         g_entity_globals.color_entity = rgb;
481                                         NormalizeColor( g_entity_globals.color_entity );
482
483                                         char buffer[128];
484                                         sprintf( buffer, "%g %g %g", g_entity_globals.color_entity[0],
485                                                          g_entity_globals.color_entity[1],
486                                                          g_entity_globals.color_entity[2] );
487
488                                         Scene_EntitySetKeyValue_Selected( "_color", buffer );
489                                 }
490                         }
491                 }
492         }
493 }
494
495 void Entity_setColour(){
496         if ( GlobalSelectionSystem().countSelected() != 0 ) {
497                 bool normalize = false;
498                 const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path();
499                 Entity* entity = Node_getEntity( path.top() );
500
501                 if ( entity != 0 ) {
502                         const char* strColor = entity->getKeyValue( "_color" );
503                         if ( !string_empty( strColor ) ) {
504                                 Vector3 rgb;
505                                 if ( string_parse_vector3( strColor, rgb ) ) {
506                                         g_entity_globals.color_entity = rgb;
507                                 }
508                         }
509
510                         if ( g_pGameDescription->mGameType == "doom3" ) {
511                                 normalize = false;
512                         }
513
514                         if ( color_dialog( MainFrame_getWindow(), g_entity_globals.color_entity ) ) {
515                                 if ( normalize ) {
516                                         NormalizeColor( g_entity_globals.color_entity );
517                                 }
518
519                                 char buffer[128];
520                                 sprintf( buffer, "%g %g %g", g_entity_globals.color_entity[0],
521                                                  g_entity_globals.color_entity[1],
522                                                  g_entity_globals.color_entity[2] );
523
524                                 Scene_EntitySetKeyValue_Selected( "_color", buffer );
525                         }
526                 }
527         }
528 }
529
530 CopiedString g_strLastModelFolder = "";
531
532 const char *getLastModelFolderPath(){
533         if ( g_strLastModelFolder.empty() ) {
534                 GlobalPreferenceSystem().registerPreference( "LastModelFolder", make_property_string( g_strLastModelFolder ) );
535                 if ( g_strLastModelFolder.empty() ) {
536                         StringOutputStream buffer( 1024 );
537                         buffer << g_qeglobals.m_userGamePath.c_str() << "models/";
538                         if ( !file_readable( buffer.c_str() ) ) {
539                                 // just go to fsmain
540                                 buffer.clear();
541                                 buffer << g_qeglobals.m_userGamePath.c_str() << "/";
542                         }
543                         g_strLastModelFolder = buffer.c_str();
544                 }
545         }
546         return g_strLastModelFolder.c_str();
547 }
548
549 const char *misc_model_dialog( ui::Widget parent ){
550         const char *filename = parent.file_dialog( TRUE, "Choose Model", getLastModelFolderPath(), ModelLoader::Name() );
551
552         if ( filename != NULL ) {
553                 g_strLastModelFolder = g_path_get_dirname( filename );
554                 // use VFS to get the correct relative path
555                 const char *relative = path_make_relative( filename, GlobalFileSystem().findRoot( filename ) );
556                 if ( relative == filename ) {
557                         globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n";
558                 }
559                 return relative;
560         }
561         return 0;
562 }
563
564 struct LightRadii {
565         static void Export(const EntityCreator &self, const Callback<void(bool)> &returnz) {
566                 returnz(self.getLightRadii());
567         }
568
569         static void Import(EntityCreator &self, bool value) {
570                 self.setLightRadii(value);
571         }
572 };
573
574 void Entity_constructPreferences( PreferencesPage& page ){
575         page.appendCheckBox(
576                         "Show", "Light Radii",
577                         make_property<LightRadii>(GlobalEntityCreator())
578         );
579 }
580 void Entity_constructPage( PreferenceGroup& group ){
581         PreferencesPage page( group.createPage( "Entities", "Entity Display Preferences" ) );
582         Entity_constructPreferences( page );
583 }
584
585 void Entity_registerPreferencesPage(){
586         PreferencesDialog_addDisplayPage( makeCallbackF(Entity_constructPage) );
587 }
588
589
590 void Entity_constructMenu( ui::Menu menu ){
591         create_menu_item_with_mnemonic( menu, "_Regroup", "GroupSelection" );
592         create_menu_item_with_mnemonic( menu, "_Ungroup", "UngroupSelection" );
593         create_menu_item_with_mnemonic( menu, "_Connect", "ConnectSelection" );
594         create_menu_item_with_mnemonic( menu, "_KillConnect", "KillConnectSelection" );
595         create_menu_item_with_mnemonic( menu, "_Select Color...", "EntityColor" );
596         create_menu_item_with_mnemonic( menu, "_Normalize Color...", "NormalizeColor" );
597 }
598
599
600 void Entity_Construct(){
601         GlobalCommands_insert( "EntityColor", makeCallbackF(Entity_setColour), Accelerator( 'K' ) );
602         GlobalCommands_insert( "NormalizeColor", makeCallbackF(Entity_normalizeColor) );
603         GlobalCommands_insert( "ConnectSelection", makeCallbackF(Entity_connectSelected), Accelerator( 'K', (GdkModifierType)GDK_CONTROL_MASK ) );
604         GlobalCommands_insert( "KillConnectSelection", makeCallbackF(Entity_killconnectSelected), Accelerator( 'K', (GdkModifierType)( GDK_SHIFT_MASK ) ) );
605         GlobalCommands_insert( "GroupSelection", makeCallbackF(Entity_groupSelected) );
606         GlobalCommands_insert( "UngroupSelection", makeCallbackF(Entity_ungroupSelected) );
607
608         GlobalPreferenceSystem().registerPreference( "SI_Colors5", make_property_string( g_entity_globals.color_entity ) );
609         GlobalPreferenceSystem().registerPreference( "LastLightIntensity", make_property_string( g_iLastLightIntensity ) );
610
611         Entity_registerPreferencesPage();
612 }
613
614 void Entity_Destroy(){
615 }