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