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