]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/entity.cpp
initial
[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 "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
160 void Entity_connectSelected()
161 {
162   if(GlobalSelectionSystem().countSelected() == 2)
163   {
164     GlobalEntityCreator().connectEntities(
165       GlobalSelectionSystem().penultimateSelected().path(),
166       GlobalSelectionSystem().ultimateSelected().path()
167     );
168   }
169   else
170   {
171     globalErrorStream() << "entityConnectSelected: exactly two instances must be selected\n";
172   }
173 }
174
175 AABB Doom3Light_getBounds(const AABB& workzone)
176 {
177   AABB aabb(workzone);
178
179   Vector3 defaultRadius(300, 300, 300);
180   if(!string_parse_vector3(EntityClass_valueForKey(*GlobalEntityClassManager().findOrInsert("light", false), "light_radius"), defaultRadius))
181   {
182     globalErrorStream() << "Doom3Light_getBounds: failed to parse default light radius\n";
183   }
184
185   if(aabb.extents[0] == 0)
186   {
187     aabb.extents[0] = defaultRadius[0];
188   }
189   if(aabb.extents[1] == 0)
190   {
191     aabb.extents[1] = defaultRadius[1];
192   }
193   if(aabb.extents[2] == 0)
194   {
195     aabb.extents[2] = defaultRadius[2];
196   }
197
198   if(aabb_valid(aabb))
199   {
200     return aabb;
201   }
202   return AABB(Vector3(0, 0, 0), Vector3(64, 64, 64));
203 }
204
205 int g_iLastLightIntensity;
206
207 void Entity_createFromSelection(const char* name, const Vector3& origin)
208 {
209 #if 0
210   if(string_equal_nocase(name, "worldspawn"))
211   {
212     gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "Can't create an entity with worldspawn.", "info");
213     return;
214   }
215 #endif
216
217   EntityClass* entityClass = GlobalEntityClassManager().findOrInsert(name, true);
218
219   bool isModel = string_equal_nocase(name, "misc_model")
220     || string_equal_nocase(name, "misc_gamemodel")
221     || string_equal_nocase(name, "model_static")
222     || (GlobalSelectionSystem().countSelected() == 0 && string_equal_nocase(name, "func_static"));
223
224   bool brushesSelected = Scene_countSelectedBrushes(GlobalSceneGraph()) != 0;
225
226   if(!(entityClass->fixedsize || isModel) && !brushesSelected)
227   {
228     globalErrorStream() << "failed to create a group entity - no brushes are selected\n";
229     return;
230   }
231
232   AABB workzone(aabb_for_minmax(Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max));
233
234
235   NodeSmartReference node(GlobalEntityCreator().createEntity(entityClass));
236
237   Node_getTraversable(GlobalSceneGraph().root())->insert(node);
238
239   scene::Path entitypath(makeReference(GlobalSceneGraph().root()));
240   entitypath.push(makeReference(node.get()));
241   scene::Instance& instance = findInstance(entitypath);
242
243   if(entityClass->fixedsize || (isModel && !brushesSelected))
244   {
245     Select_Delete();
246     
247     Transformable* transform = Instance_getTransformable(instance);
248     if(transform != 0)
249     {
250       transform->setType(TRANSFORM_PRIMITIVE);
251       transform->setTranslation(origin);
252       transform->freezeTransform();
253     }
254
255     GlobalSelectionSystem().setSelectedAll(false);
256
257     Instance_setSelected(instance, true);
258   }
259   else
260   {
261     if (g_pGameDescription->mGameType == "doom3")
262     {
263       Node_getEntity(node)->setKeyValue("model", Node_getEntity(node)->getKeyValue("name"));
264     }
265
266     Scene_parentSelectedBrushesToEntity(GlobalSceneGraph(), node);
267     Scene_forEachChildSelectable(SelectableSetSelected(true), instance.path());
268   }
269
270   // tweaking: when right clic dropping a light entity, ask for light value in a custom dialog box
271   // see SF bug 105383
272
273   if (g_pGameDescription->mGameType == "hl")
274   {
275     // FIXME - Hydra: really we need a combined light AND color dialog for halflife.
276     if (string_equal_nocase(name, "light")
277       || string_equal_nocase(name, "light_environment")
278       || string_equal_nocase(name, "light_spot"))
279     {
280       int intensity = g_iLastLightIntensity;
281
282       if (DoLightIntensityDlg (&intensity) == eIDOK)
283       {
284         g_iLastLightIntensity = intensity;
285         char buf[30];
286         sprintf( buf, "255 255 255 %d", intensity );
287         Node_getEntity(node)->setKeyValue("_light", buf);
288       }
289     }
290   }
291   else if(string_equal_nocase(name, "light"))
292   {
293     if(g_pGameDescription->mGameType != "doom3")
294     {
295       int intensity = g_iLastLightIntensity;
296
297       if (DoLightIntensityDlg (&intensity) == eIDOK)
298       {
299         g_iLastLightIntensity = intensity;
300         char buf[10];
301         sprintf( buf, "%d", intensity );
302         Node_getEntity(node)->setKeyValue("light", buf);
303       }
304     }
305     else if(brushesSelected) // use workzone to set light position/size for doom3 lights, if there are brushes selected
306     {
307       AABB bounds(Doom3Light_getBounds(workzone));
308       StringOutputStream key(64);
309       key << bounds.origin[0] << " " << bounds.origin[1] << " " << bounds.origin[2];
310       Node_getEntity(node)->setKeyValue("origin", key.c_str());
311       key.clear();
312       key << bounds.extents[0] << " " << bounds.extents[1] << " " << bounds.extents[2];
313       Node_getEntity(node)->setKeyValue("light_radius", key.c_str());
314     }
315   }
316
317   if(isModel)
318   {
319     const char* model = misc_model_dialog(GTK_WIDGET(MainFrame_getWindow()));
320     if(model != 0)
321     {
322       Node_getEntity(node)->setKeyValue("model", model);
323     }
324   }
325 }
326
327
328 bool DoNormalisedColor(Vector3& color)
329 {
330   if(!color_dialog(GTK_WIDGET(MainFrame_getWindow()), color))
331     return false;
332   /* 
333   ** scale colors so that at least one component is at 1.0F 
334   */
335
336   float largest = 0.0F;
337
338   if ( color[0] > largest )
339     largest = color[0];
340   if ( color[1] > largest )
341     largest = color[1];
342   if ( color[2] > largest )
343     largest = color[2];
344
345   if ( largest == 0.0F )
346   {
347     color[0] = 1.0F;
348     color[1] = 1.0F;
349     color[2] = 1.0F;
350   }
351   else
352   {
353     float scaler = 1.0F / largest;
354
355     color[0] *= scaler;
356     color[1] *= scaler;
357     color[2] *= scaler;
358   }
359
360   return true;
361 }
362
363 void Entity_setColour()
364 {
365   if(GlobalSelectionSystem().countSelected() != 0)
366   {
367     const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path();
368     Entity* entity = Node_getEntity(path.top());
369     if(entity != 0)
370     {
371       const char* strColor = entity->getKeyValue("_color");
372       if(!string_empty(strColor))
373       {
374         Vector3 rgb;
375         if (string_parse_vector3(strColor, rgb))
376         {
377           g_entity_globals.color_entity = rgb;
378         }
379       }
380
381       if(g_pGameDescription->mGameType == "doom3"
382         ? color_dialog(GTK_WIDGET(MainFrame_getWindow()), g_entity_globals.color_entity)
383         : DoNormalisedColor(g_entity_globals.color_entity))
384       {
385         char buffer[128];
386         sprintf(buffer, "%g %g %g", g_entity_globals.color_entity[0],
387                 g_entity_globals.color_entity[1],
388                 g_entity_globals.color_entity[2]);
389
390         Scene_EntitySetKeyValue_Selected("_color", buffer);
391       }
392     }
393   }
394 }
395
396 const char* misc_model_dialog(GtkWidget* parent)
397 {
398   StringOutputStream buffer(1024);
399
400   buffer << g_qeglobals.m_userGamePath.c_str() << "models/";
401
402   if(!file_readable(buffer.c_str()))
403   {
404     // just go to fsmain
405     buffer.clear();
406     buffer << g_qeglobals.m_userGamePath.c_str() << "/";
407   }
408
409   const char *filename = file_dialog (parent, TRUE, "Choose Model", buffer.c_str(), ModelLoader::Name());
410   if (filename != 0)
411   {
412     // use VFS to get the correct relative path
413     const char* relative = path_make_relative(filename, GlobalFileSystem().findRoot(filename));
414     if(relative == filename)
415     {
416       globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n";
417     }
418     return relative;
419   }
420   return 0;
421 }
422
423 void LightRadiiImport(EntityCreator& self, bool value)
424 {
425   self.setLightRadii(value);
426 }
427 typedef ReferenceCaller1<EntityCreator, bool, LightRadiiImport> LightRadiiImportCaller;
428
429 void LightRadiiExport(EntityCreator& self, const BoolImportCallback& importer)
430 {
431   importer(self.getLightRadii());
432 }
433 typedef ReferenceCaller1<EntityCreator, const BoolImportCallback&, LightRadiiExport> LightRadiiExportCaller;
434
435 void Entity_constructPreferences(PreferencesPage& page)
436 {
437   page.appendCheckBox(
438     "Show", "Light Radii",
439     LightRadiiImportCaller(GlobalEntityCreator()),
440     LightRadiiExportCaller(GlobalEntityCreator())
441   );
442 }
443 void Entity_constructPage(PreferenceGroup& group)
444 {
445   PreferencesPage page(group.createPage("Entities", "Entity Display Preferences"));
446   Entity_constructPreferences(page);
447 }
448 void Entity_registerPreferencesPage()
449 {
450   PreferencesDialog_addDisplayPage(FreeCaller1<PreferenceGroup&, Entity_constructPage>());
451 }
452
453
454
455 void Entity_constructMenu(GtkMenu* menu)
456 {
457   create_menu_item_with_mnemonic(menu, "_Ungroup", "UngroupSelection");
458   create_menu_item_with_mnemonic(menu, "_Connect", "ConnectSelection");
459   create_menu_item_with_mnemonic(menu, "_Select Color...", "EntityColor");
460 }
461
462
463
464 #include "preferencesystem.h"
465 #include "stringio.h"
466
467 void Entity_Construct()
468 {
469   GlobalCommands_insert("EntityColor", FreeCaller<Entity_setColour>(), Accelerator('K'));
470   GlobalCommands_insert("ConnectSelection", FreeCaller<Entity_connectSelected>(), Accelerator('K', (GdkModifierType)GDK_CONTROL_MASK));
471   GlobalCommands_insert("UngroupSelection", FreeCaller<Entity_ungroupSelected>());
472
473   GlobalPreferenceSystem().registerPreference("SI_Colors5", Vector3ImportStringCaller(g_entity_globals.color_entity), Vector3ExportStringCaller(g_entity_globals.color_entity));
474   GlobalPreferenceSystem().registerPreference("LastLightIntensity", IntImportStringCaller(g_iLastLightIntensity), IntExportStringCaller(g_iLastLightIntensity));
475
476   Entity_registerPreferencesPage();
477 }
478
479 void Entity_Destroy()
480 {
481 }
482