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